9

I'm stuck on something:

I deserialized a JSON file using JObject.Load:

// get the JSON into an object 
JObject jsonObject = JObject.Load(new
  JsonTextReader(new StreamReader("mydoc.json")));

Fine. I now have a populate jsonObject.

Now I iterate through its properties like this:

foreach (JProperty jsonRootProperty in jsonObject.Properties())
  {    
    if (jsonRootProperty.Name=="Hotel")
    {
      ... !!! I just want a JObject here...
    }
  }

Once I find a property with a Name equal to "Hotel", I want that property's value as a JObject. The catch is that the Hotel property name might be a single value (say, a string), or it might be a JSON object or a JSON array.

How can I get the property's value into a JObject variable so that I can pass it to another function that accepts a JObject parameter?

Jazimov
  • 12,626
  • 9
  • 52
  • 59

1 Answers1

15

Get the Value of the JProperty, which is a JToken, and look at its Type. This property will tell you if the token is an Object, Array, String, etc. If the token type is Object, then you can simply cast it to a JObject and pass it to your function. If the token type is something other than Object and your function has to have a JObject, then you'll need to wrap the value in a JObject in order to make it work.

foreach (JProperty jsonRootProperty in jsonObject.Properties())
{    
    if (jsonRootProperty.Name=="Hotel")
    {
        JToken value = jsonRootProperty.Value;
        if (value.Type == JTokenType.Object)
        {
            FunctionThatAcceptsJObject((JObject)value);
        }
        else
        {
            FunctionThatAcceptsJObject(new JObject(new JProperty("value", value)));
        }
    }
}
Brian Rogers
  • 125,747
  • 31
  • 299
  • 300
  • (Off subject but I am a great admirer of you, your knowledge of JSON.NET, and willingness to share it--thank you for replying). Looks good but can you please explain more about "wrap the value in a JObject"? I wasted many hours struggling with how to get a JToken into a JObject and clearly I'm missing something about how JTokens and JObjects relate to each other... – Jazimov Jul 05 '16 at 15:42
  • The first part of [this answer](http://stackoverflow.com/q/38005957/10263) might help you then. It talks about how JToken, JObject, etc. relate. Thanks for the kind words. – Brian Rogers Jul 05 '16 at 15:46
  • Awesome! That link looks like a treasure-trove of additional information. That, along your answer here, should set me on the right path to jump these final JSON.NET hurdles! – Jazimov Jul 05 '16 at 15:54