问题描述
我正在使用 NewtonSoft JObject 解析 JSON 字符串.如何以编程方式从动态对象中获取值?我想简化代码,不要为每个对象重复自己.
I'm parsing a JSON string using the NewtonSoft JObject. How can I get values from a dynamic object programmatically? I want to simplify the code to not repeat myself for every object.
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"语句中的代码块提取到单独的方法中,例如:
Is there any way I can extract the code blocks in the "if" statements to a separate method e.g:
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?
Is it even possible since we can't use reflection for dynamic objects. Or am I even using the JObject correctly?
谢谢.
推荐答案
假设您使用的是 Newtonsoft.Json.Linq.JObject,则不需要使用动态.JObject 类可以采用字符串索引器,就像字典一样:
Assuming you're using the Newtonsoft.Json.Linq.JObject, you don't need to use dynamic. The JObject class can take a string indexer, just like a dictionary:
JObject myResult = GetMyResult();
returnObject.Id = myResult["string here"]["id"];
希望这会有所帮助!
这篇关于如何以编程方式从动态 JObject 获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!