如何以编程方式从动态JObject获取属性 [英] How to get property from dynamic JObject programmatically

查看:455
本文介绍了如何以编程方式从动态JObject获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆