How do I enumerate through a JObject?

前端 未结 4 2117
暗喜
暗喜 2020-11-28 05:52

I\'m trying to determine how to access the data that is in my JObject and I can\'t for the life of me determine how to use it.

JObject Object = (JObject)Resp         


        
相关标签:
4条回答
  • 2020-11-28 06:23

    The answer did not work for me. I dont know how it got so many votes. Though it helped in pointing me in a direction.

    This is the answer that worked for me:

    foreach (var x in jobj)
    {
        var key = ((JProperty) (x)).Name;
        var jvalue = ((JProperty)(x)).Value ;
    }
    
    0 讨论(0)
  • 2020-11-28 06:31

    If you look at the documentation for JObject, you will see that it implements IEnumerable<KeyValuePair<string, JToken>>. So, you can iterate over it simply using a foreach:

    foreach (var x in obj)
    {
        string name = x.Key;
        JToken value = x.Value;
        …
    }
    
    0 讨论(0)
  • 2020-11-28 06:37

    For people like me, linq addicts, and based on svick's answer, here a linq approach:

    using System.Linq;
    //...
    //make it linq iterable. 
    var obj_linq = Response.Cast<KeyValuePair<string, JToken>>();
    

    Now you can make linq expressions like:

    JToken x = obj_linq
              .Where( d => d.Key == "my_key")
              .Select(v => v)
              .FirstOrDefault()
              .Value;
    string y = ((JValue)x).Value;
    

    Or just:

    var y = obj_linq
           .Where(d => d.Key == "my_key")
           .Select(v => ((JValue)v.Value).Value)
           .FirstOrDefault();
    

    Or this one to iterate over all data:

    obj_linq.ToList().ForEach( x => { do stuff } ); 
    
    0 讨论(0)
  • 2020-11-28 06:41

    JObjects can be enumerated via JProperty objects by casting it to a JToken:

    foreach (JProperty x in (JToken)obj) { // if 'obj' is a JObject
        string name = x.Name;
        JToken value = x.Value;
    }
    

    If you have a nested JObject inside of another JObject, you don't need to cast because the accessor will return a JToken:

    foreach (JProperty x in obj["otherObject"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects
        string name = x.Name;
        JToken value = x.Value;
    }
    
    0 讨论(0)
提交回复
热议问题