Blog
Newtonsoft JObjects and JTokens
Newtonsoft JObjects and JTokens
If you’ve developed with Newtonsoft’s JSON framework, you’ve likely used the JObject and JToken classes to locate a subset of JSON within deserialized JSON. There is an interesting difference between these two classes and how they handle null attributes/properties.
First, let’s consider the following JSON Object:
{
‘contactid’: ‘9F5325A3-C2AB-448E-83B6-5B983200222F’,
‘firstname’: ‘Amber unlinked’,
‘parentcustomerid_account’: null,
‘parentcustomerid_contact’: ‘abc’
}
Let’s imagine that we are receiving this JSON from an API and we may not always receive the same properties in each call. If we wanted to check that the JSON file contains the ‘parentcustomerid_account’ property, regardless is its value is null, how would we do that? You might be tempted to add something like:
JObject myProperty = myJsonDataset[“parentcustomerid_account”];
if (myProperty != null)————or————
JProperty myProperty = myJsonDataset[“parentcustomerid_account”];
if (myProperty != null)
JObject example
This code’s If statements will never be satisfied. This is because Newtonsoft can not set a JObject from a property with a null value; the JObject myProperty will contain no JSON properties at all. You could replace the above code with any property name that isn’t part of your JSON file and you will get the same behavior:
JObject myProperty = myJsonDataset[“aRandomField”];
if (myProperty != null)//This code will behave the same way as the code above- the If condition will never be satisfied
JToken example
How then, can be discern the difference between the two? One of the ways I like to handle this is with the JToken class. The JToken class represents JSON who’s type (Object, Array, Property, etc) will be determined at run-time based on the JSON you feed it. In our case, we have a property with a null value, and we can now check to see if the property actually came over in our original file:
JToken myProperty = myJsonDataset[“parentcustomerid_account”];
if (myProperty != null)//This If condition will be satisfied so long as the property is in the JSON file
If you’re like me, you don’t like using strongly typed classes or hefty try/catches for little things like this. So, if you doubt the content of the JSON file you are receiving, use JTokens to let Newtonsoft determine what kind of JSON you are looking at.
Contact Beringer Today!
We love developing with Newtonsoft to help us build bigger & stronger integrations with Microsoft Dynamics and Azure. Beringer Technology Group, a leading Microsoft Gold Certified Partner specializing in Microsoft Dynamics 365 and CRM for Distribution. We also provide expert Managed IT Services, Backup and Disaster Recovery, Cloud Based Computing and Unified Communication Solutions.