How to get property from dynamic JObject programmatically

前端 未结 3 576
甜味超标
甜味超标 2020-12-09 16:51

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 ev

相关标签:
3条回答
  • 2020-12-09 17:02

    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

    [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);
    
    0 讨论(0)
  • 2020-12-09 17:27

    Another way of targeting this is by using SelectToken (Assuming that you're using 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

    0 讨论(0)
  • 2020-12-09 17:28

    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"];
    

    Hope this helps!

    0 讨论(0)
提交回复
热议问题