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.
In Visual Studio go to Tools -> NuGet Package Manager -> Package Manager Console and execute the below command.
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.
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.
Output of the above code snippet is shown as
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.
Output for this is:
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.
Output will be as shown:
If you have any feedback on this post please let me know by using the comments section.