Categories
.NET Core

Understanding the Newtonsoft JSON Token

One of the concepts worth understanding when writing a custom converter for the popular Newtonsoft JSON framework is that of the JsonToken, and the role it plays in helping you understand the JSON being read.

The JsonToken documentation for Newtonsoft is relatively sparse – in part because once you understand it, it’s a relatively simple concept.

Effectively, when you’re attempting to deserialise a string representation of a JSON object, such as in the ReadJson method of a custom JsonConverter, the JsonToken represents each element or component (token if you prefer) of the object as it’s deserialised.

So for example, if you have the following JSON and implement the ReadJson method:

{	"message": "Hello world"}

When you first get the reader.TokenType value you’ll get JsonToken.StartObject back – this represents that the { implies that you’re first reading an object element.

If you were to then call reader.ReadAsync(), and then subsequently request the reader.TokenType again now you’ll get JsonToken.PropertyName in response. This is because the next element within the JSON string is the property name (in other words, the “message” key).

Lastly, if you were to call reader.ReadAsync() for a third time, you’d get back JsonToken.String as the value of the property is a string (“Hello world”). NewtonSoft will try and parse the value into a representation of a type – so for example, if that was a number, you’d get back Integer of Float, and if it was a Boolean you’d get back Boolean.