Search code examples
c#json.net

Differentiating between Json.Linq.JValue and Json.Linq.JObject


I am trying to parse a JSON string, the issue is the API would return an empty string which is in the form on a Linq.JValue datatype and the other time it would return a child with type Linq.JObject. I want to handle both the responses in a dynamic manner, I am struggling to differentiate these two.

Example responses -

"ITEMIZEDCHARGES": {
      "ITEM": [
        {
          "@TYPE": "CHARGE",
          "@FOR": "FREIGHT",
          "@AMOUNT": "627.28",
          "@DESCRIPTION": "400 LB CL50, 3 PLT @ 48 x 48 x 48 IN"
        },
        {
          "@TYPE": "CHARGE",
          "@FOR": "FSC",
          "@AMOUNT": "161.84",
          "@DESCRIPTION": "/ FUEL SURCHARGE",
          "@RATE": "25.8%"
        }
      ]
    },
    

   Or 

"ITEMIZEDCHARGES" : ""

IMG : https://i.sstatic.net/9vYL9.jpg


Solution

  • You can check the type of the value for ITEMIZEDCHARGES then go according to what you expect by using GetType() on its value and comparing it with either typeof(JObject) or typeof(JValue).

    public class Item
    {
        [JsonProperty("@TYPE")]
        public string Type { get; set; }
        [JsonProperty("@FOR")]
        public string For { get; set; }
        // ....
    }
    
    var jObj = JObject.Parse(jsonString);
    
    List<Item> yourObject = null;
    if (jObj["ITEMIZEDCHARGES"].GetType().Equals(typeof(JObject)))
    {
        Console.WriteLine("Its a JObject");
        yourObject = jObj["ITEMIZEDCHARGES"]["ITEM"].ToObject<List<Item>>();
    }
    
    else if (jObj["ITEMIZEDCHARGES"].GetType().Equals(typeof(JValue)))
        Console.WriteLine("Its a String value");
    
    

    You will need to do other checks to make sure the keys exist in your object.