【发布时间】:2013-04-12 10:37:05
【问题描述】:
我正在使用 NewtonSoft JObject 解析 JSON 字符串。 如何以编程方式从动态对象中获取值? 我想简化代码,不要为每个对象重复自己。
public ExampleObject GetExampleObject(string jsonString)
{
ExampleObject returnObject = new ExampleObject();
dynamic dynamicResult = JObject.Parse(jsonString);
if (!ReferenceEquals(dynamicResult.album, null))
{
//code block to extract to another method if possible
returnObject.Id = dynamicResult.album.id;
returnObject.Name = dynamicResult.album.name;
returnObject.Description = dynamicResult.albumsdescription;
//etc..
}
else if(!ReferenceEquals(dynamicResult.photo, null))
{
//duplicated here
returnObject.Id = dynamicResult.photo.id;
returnObject.Name = dynamicResult.photo.name;
returnObject.Description = dynamicResult.photo.description;
//etc..
}
else if..
//etc..
return returnObject;
}
有什么方法可以将“if”语句中的代码块提取到单独的方法中,例如:
private void ExampleObject GetExampleObject([string of desired type goes here? album/photo/etc])
{
ExampleObject returnObject = new ExampleObject();
returnObject.Id = dynamicResult.[something goes here?].id;
returnObject.Name = dynamicResult.[something goes here?].name;
//etc..
return returnObject;
}
是否有可能,因为我们不能对动态对象使用反射。或者我是否正确使用了 JObject?
谢谢。
【问题讨论】:
-
jsonString 是您控制的字符串吗?还是您从另一方收到此信息,您需要与它沟通?
-
@MichaelD 它来自另一方。我只是接收和解析。
标签: c# .net json json.net deserialization