如何以编程方式从动态JObject获取属性

dcd*_*oid 19 .net c# json json.net deserialization

我正在使用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;
}
Run Code Online (Sandbox Code Playgroud)

有什么办法可以将"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;
}
Run Code Online (Sandbox Code Playgroud)

它是否可能,因为我们不能将反射用于动态对象.或者我甚至正确使用JObject?

谢谢.

Con*_*des 32

假设您使用的是Newtonsoft.Json.Linq.JObject,则无需使用动态.JObject类可以使用字符串索引器,就像字典一样:

JObject myResult = GetMyResult();
returnObject.Id = myResult["string here"]["id"];
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助!

  • 什么在`["字符串在这里"]`?不会"id"只返回对象中的ID值吗? (8认同)
  • @joelforsyth,是的,您可能会这样做,具体取决于对象结构,例如`returnObject.Id = (int)myResult["id"]; ` (2认同)

Zia*_*iki 6

另一种定位方法是使用SelectToken(假设您正在使用Newtonsoft.Json):

JObject json = GetResponse();
var name = json.SelectToken("items[0].name");
Run Code Online (Sandbox Code Playgroud)

有关完整文档: https: //www.newtonsoft.com/json/help/html/SelectToken.htm