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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16097768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 23:59:15  来源:igfitidea点击:

How to get property from dynamic JObject programmatically

c#.netjsonjson.netdeserialization

提问by dcdroid

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.

我正在使用 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;
}

Is there any way I can extract the code blocks in the "if" statements to a separate method e.g:

有什么方法可以将“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;
}

Is it even possible since we can't use reflection for dynamic objects. Or am I even using the JObject correctly?

甚至可能因为我们不能对动态对象使用反射。或者我什至正确使用 JObject 吗?

Thanks.

谢谢。

采纳答案by Connie Hilarides

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:

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

JObject myResult = GetMyResult();
returnObject.Id = myResult["string here"]["id"];

Hope this helps!

希望这可以帮助!

回答by Hamit YILDIRIM

with dynamic keyword like below:

使用动态关键字如下:

private static JsonSerializerSettings jsonSettings;

private static T Deserialize<T>(string jsonData)
{
   return JsonConvert.DeserializeObject<T>(jsonData, jsonSettings);
}

//if you know what will return

//如果你知道会返回什么

var jresponse = Deserialize<SearchedData>(testJsonString);

//if you know return object type you should sign it with json attributes like

//如果您知道返回对象类型,您应该使用json属性对其进行签名,例如

[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public class SearchedData
{
    [JsonProperty(PropertyName = "Currency")]
    public string Currency { get; set; }
    [JsonProperty(PropertyName = "Routes")]
    public List<List<Route>> Routes { get; set; }
}

// if you don't know the return type use dynamic as generic type

// 如果您不知道返回类型,请使用动态作为泛型类型

var jresponse = Deserialize<dynamic>(testJsonString);

回答by Ziad Akiki

Another way of targeting this is by using SelectToken(Assuming that you're using Newtonsoft.Json):

另一种针对此的方法是使用SelectToken(假设您正在使用Newtonsoft.Json):

JObject json = GetResponse();
var name = json.SelectToken("items[0].name");

For a full documentation: https://www.newtonsoft.com/json/help/html/SelectToken.htm

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