C #, JSON Parsing, dynamic variable. How to check type?

I am parsing JSON texts. Sometimes I get Array types and sometimes Object in the text. I tried to check the type as follows:

 dynamic obj = JsonConvert.DeserializeObject(text); //json text if (obj is Array) { Console.WriteLine("ARRAY!"); } else if (obj is Object) { Console.WriteLine("OBJECT!"); } 

I checked the types during debugging. obj has the Type property as Object when parsing objects and Array when parsing arrays. However, the console output was OBJECT! for both situations. Obviously, I am checking the type incorrectly. What is the correct way to type check?

EDIT

JSON Content:

[ {"ticket":"asd", ...}, {..} ] or { "ASD":{...}, "SDF":{...} }

In both situations, I get output as OBJECT! .

Edit # 2

I changed the type checking order as @Houssem suggested. All the same conclusion. Therefore, I also changed the OP. My code is like this right now, and I still get the same result.

+4
source share
1 answer

Try this as JSON.NET returns an object of type JToken

  if (((JToken)obj).Type == JTokenType.Array) { Console.WriteLine("ARRAY!"); } else if (((JToken)obj).Type == JTokenType.Object) { Console.WriteLine("OBJECT!"); } 
+7
source

Source: https://habr.com/ru/post/1492932/


All Articles