Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking for empty or null JToken in a JObject

Tags:

c#

sql

json.net

I have the following...

JArray clients = (JArray)clientsParsed["objects"];  foreach (JObject item in clients.Children()) {     // etc.. SQL params stuff...     command.Parameters["@MyParameter"].Value = JTokenToSql(item["thisParameter"]); } 

JTokenToSql looks like this...

public static object JTokenToSql(JToken obj) {     if (obj.Any())         return (object)obj;     else         return (object)DBNull.Value; } 

I have tried ((JObject)obj).Count also.. But doesn't seem to be working.

like image 871
Kyle Avatar asked Jun 05 '14 17:06

Kyle


People also ask

Is a JObject a JToken?

So you see, a JObject is a JContainer , which is a JToken . Here's the basic rule of thumb: If you know you have an object (denoted by curly braces { and } in JSON), use JObject.

How do you access JObject values?

The simplest way to get a value from LINQ to JSON is to use the Item[Object] index on JObject/JArray and then cast the returned JValue to the type you want. JObject/JArray can also be queried using LINQ.

What is JToken in C#?

JToken is the abstract base class of JObject , JArray , JProperty , and JValue , which represent pieces of JSON data after they have been parsed. JsonToken is an enum that is used by JsonReader and JsonWriter to indicate which type of token is being read or written.


2 Answers

To check whether a property exists on a JObject, you can use the square bracket syntax and see whether the result is null or not. If the property exists, a JToken will be always be returned (even if it has the value null in the JSON).

JToken token = jObject["param"]; if (token != null) {     // the "param" property exists } 

If you have a JToken in hand and you want to see if it is non-empty, well, that depends on what type of JToken it is and how you define "empty". I usually use an extension method like this:

public static class JsonExtensions {     public static bool IsNullOrEmpty(this JToken token)     {         return (token == null) ||                (token.Type == JTokenType.Array && !token.HasValues) ||                (token.Type == JTokenType.Object && !token.HasValues) ||                (token.Type == JTokenType.String && token.ToString() == String.Empty) ||                (token.Type == JTokenType.Null);     } } 
like image 149
Brian Rogers Avatar answered Sep 21 '22 10:09

Brian Rogers


You can proceed as follows to check whether a JToken Value is null

JToken token = jObject["key"];  if(token.Type == JTokenType.Null) {     // Do your logic } 
like image 41
Sam Ngugi Avatar answered Sep 18 '22 10:09

Sam Ngugi