14

Using JSON.Net, how do I get the native type of a value in a JSON file? Namely, I'm after simply if it's a string (value enclosed in quotations) or not.

var json = (JObject) JsonConvert.DeserializeObject(newVersion.JSON);
foreach (var data in json)
{
    if(data.value IS STRING){

    }
}
Tom Gullen
  • 61,249
  • 84
  • 283
  • 456

2 Answers2

9

You can simply check the Type property of each JToken in your list:

foreach (var data in json)
{
    if (data.Value.Type == JTokenType.String)
        // ...
    }
}

See JTokenType

haim770
  • 48,394
  • 7
  • 105
  • 133
  • 2
    in my case Type gets always == property, I was expecting to see array or object but I just says property – Oswaldo Zapata Jan 16 '18 at 21:22
  • 1
    This property doesn't exist :( – A X Dec 05 '20 at 18:08
  • @AX, What property exactly? – haim770 Dec 05 '20 at 19:57
  • 1
    JToken now has a Type property directly (no longer necessary to go through Value). https://www.newtonsoft.com/json/help/html/P_Newtonsoft_Json_Linq_JValue_Type.htm. If the property does not exist and you are sure that it's a JToken, maybe you need a cast (e.g. maybe at runtime it is just an 'object' for example and does not know about the 'Type' property). – Brecht De Rooms Jun 01 '21 at 14:20
3

You can refer to this answer

Parse the json string via

var token = JToken.Parse(content);

Make use of JToken to identify its type,

if (token is JArray) {

} else if (token is JValue) {

} else if (token is JObject) {

}
Nicholas
  • 1,883
  • 21
  • 39