Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if object is JProperty or JArray

Tags:

json.net

Given the two JTokens:

{ "Users": { "Name": "Carl" } }

and

{ "Users": [ { "Name": "Carl" }, {"Name": "Peter"} ] }

How can I tell if Users is a JProperty or JObject/JArray?

I need loop Users with

foreach (JObject User in myjobject["Users"]) { ... }

Solution It was as simple as myjobject["Users"].GetType(). However, that didn't work in the Watch debugger window, but it worked at runtime. Hrmpff.

like image 571
Pål Thingbø Avatar asked Aug 11 '13 13:08

Pål Thingbø


People also ask

What is JArray?

JArray(Object[]) Initializes a new instance of the JArray class with the specified content. JArray(JArray) Initializes a new instance of the JArray class from another JArray object.

How do I declare JArray?

JArray addresses = new JArray(); foreach (AddressModel address in contactAddresses) { addresses. Add(JObject. Parse( @"{""street"":""" + address. Street + @"""city"":""" + address.

How do I convert JArray to JObject?

it is easy, JArray myarray = new JArray(); JObject myobj = new JObject(); // myobj.


1 Answers

The Type property will tell you the type of the token you have.

switch(token.Type)
{
     case JTokenType.Array:
         break;
     case JTokenType.String:
         break;
}
like image 186
James Newton-King Avatar answered Sep 26 '22 15:09

James Newton-King