0

If I have a json object like this:

{
    "name": "value"
}

I can do jobjectCurrent["name"] and get the reference to that object.

However, if I have a json like this:

{
    "items":[]
}

I can NOT do jobjectCurrent["items"]. How would I find out then if items exists and if its a jarray and get a reference to the jarray so I can add items?

Is there a syntax where I can generically access normal key/value pairs as well as arrays?

stelioslogothetis
  • 9,371
  • 3
  • 28
  • 53
SledgeHammer
  • 7,338
  • 6
  • 41
  • 86
  • 2
    `jobjectCurrent["items"]` works just fine, see https://dotnetfiddle.net/sG2lCr. Could you explain your problem in more detail? – dbc Jun 19 '17 at 22:43
  • @dbc -- hmm... I just tried it again and it seems like its working now lol... might have been user error before... I'll keep down this path and see if it works, if not, I'll respond again. Thx. – SledgeHammer Jun 19 '17 at 22:54
  • @dbc Ok... I see whats going on... json.net is structured in a way where they have different hierarchy of objects... I.e. jArray and jObject are not compatible types, so the code gets kind of hokey. Would have been nice to have a root object that can be any type of json object. – SledgeHammer Jun 19 '17 at 23:22
  • 1
    *Would have been nice to have a root object that can be any type of json object.* -- there is such an object. Use [`JToken.Parse()`](http://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JToken_Parse.htm). See [JSON.NET: Why Use JToken--ever?](https://stackoverflow.com/a/38212978/3744182). – dbc Jun 19 '17 at 23:24
  • @dbc, oh cool. Right now my public method takes a JObject. Is there any advantage to keeping it a JObject? vs switching everything to a JToken? I dunno... a JObject seems more like the type that should go into public methods. I guess I can get the first token and switch to JTokens internally. – SledgeHammer Jun 20 '17 at 01:50
  • 1
    If your method requires that the incoming JSON be an unordered collection of key/value pairs, then use a `JObject`. If the incoming JSON is completely unconstrained, use `JToken`. – dbc Jun 20 '17 at 01:53

0 Answers0