The best way to Serialize and Deserialize JSON – using Newtonsoft Json.Net

The best way to convert JSON text to .Net object and a .Net object to JSON text is by using JsonSerializer. First of all we will create simple entity class Person.

Person Class

In Visual Studio go to Tools -> NuGet Package Manager -> Package Manager Console and execute the below command.

Nuget Newtonsoft JSON

Json.Net will now be installed into the project which is a popular high-performance JSON framework for .NET. The reference to Newtonsoft.Json will be added to the project as shown.

Reference

JsonConvert class has a method SerializeObject which we can use to convert the .Net object to JSON text. And method DeserializeObject can be used to convert JSON text back to .Net object.

SerializeObjectAndDeseroialize

Output of the above code snippet is shown as

OutPut

SerializeObject method also has an overload which takes JsonSerializerSettings as a parameter. You can read more about the available JsonSerializer settings here: Serialization Settings.

For example one can use JsonSerializerSettings to change the output date format.

newDateFormat

Output for this is:

newDateFormatOutput

To format the indentation of the output Json Text we can use the overload method SerializeObject(objectName, Formatting.Indented).
Second example for using JsonSerializerSettings, CamelCasePropertyNamesContractResolver can be used to get the JSON property name to be written in camelcase.

CamelcaseProgram

Output will be as shown:

CamelcaseProgramOutput

If you have any feedback on this post please let me know by using the comments section.

Updated: February 25, 2016 — 6:29 pm

Leave a Reply

www.CodingWebApps.com © 2015 Frontier Theme