Json.NET - Using JsonSerializer Class

In the previous post, I have detailed the serialization and deserialization functionalities using the Serialize and Deserialize methods in JsonConvert class. These methods are built on top of JsonSerializer class which is doing all the heavy lifiting during the conversion process under the hood. 

In this I will show you how to use JsonSerializer class for doing the conversion. One advantage of using this class is that we have more control over the conversion process. It exposes different properties through which we can control how Json.Net will serialize/deserialize the json

So let's add one more property EffectiveDate which is a DateTime field to our class from the previous post 

In this example, I am using JsonSerializer class instead of JsonConvert class for doing the serialization. Unlike the latter one, using this allows me to write JSON directly to the stream using StringWriter and JsonTextWriter. Like the JsonConvert class, JsonSerializer also has a number of properties for customizing the serialization process and it allows the developer to have more control over it.  

Also in this example, I have used a converter for serializing the date, JavaScriptDateTimeConverter. If I serialized it without usng the converter the output would be like the one given below

{"ColorId":1,"ColorName":"Green","EffectiveDate":"2016-04-01T00:00:00"}

The date format will be in ISO date format But if you want to have the JavaScript Date object in your json, you can use the JavaScriptDateTimeConverter for that.


No Comments

Add a Comment