Getting data from a deeply nested json object

后端 未结 2 813
梦毁少年i
梦毁少年i 2020-12-30 06:57

I\'m really stuck on this problem now for 2 days, how can I get the data out of a deeply nested json object.

I have found an online json tools http://www.jsoneditor

相关标签:
2条回答
  • This extension method uses recursion to loop through a deep nested json and find the value for a jProperty.

          public static TType JsonValue<TType>(this JObject obj, string key)
        {
            object result = null; //default to null if nothing is found
    
            foreach (var item in obj)
            {
                var token = item;
    
                if (token.Key.Equals(key, StringComparison.InvariantCultureIgnoreCase))
                {
                    result = token.Value.ToObject<TType>(); //return the value found
                    break;
                }
    
                if (!obj[token.Key].Children().Any())
                    continue;
    
                    var jt = obj[token.Key].ToString();
    
                    if (!jt.StartsWith("["))
                    {
                      result = JsonValue<TType>(JObject.Parse(jt), key);
                    }
                    else
                    {
                        obj[token.Key].Children().ToList().ForEach(x =>
                        {
                            //only the first match will be returned
                            result = JsonValue<TType>(JObject.Parse(x.ToString()), key);
                        });
                    }
    
                if (result != null)
                    break;
    
            }
    
           return (TType)result;
        }
    

    How to use:

        var myValue = jsonObject.JsonValue<string>("propName");
        var numbValue = jsonObject.JsonValue<long?>("propName2") ?? 0; 
    
    0 讨论(0)
  • 2020-12-30 07:43

    Try this instead:

    IList<JToken> rates = root["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"].Children().ToList();
    

    EDIT:

    var rateInfo = json["HotelListResponse"]["HotelList"]["HotelSummary"][0]["RoomRateDetailsList"]["RoomRateDetails"]["RateInfos"]["RateInfo"];
    
    var result =JsonConvert.DeserializeObject<RateInfo>( rateInfo .ToString() );
    
    0 讨论(0)
提交回复
热议问题