The Newtonsoft.Json library contains a number of tools for working with JSON from within your .NET application.
New ASP.NET applications created in Visual Studio already contain a reference to the Newtonsoft.Json library. But if you want to add the library to a different project type or if you want to update the version installed by default with an ASP.NET application, you can right-click your project in the Visual Studio Solution Explorer and select "Manage NuGet Package..." and search for Newtonsoft.Json. Select the "Newtonsoft.Json" package (Fig 1) and click either "Install" or "Update".
Newtonsoft is very good at serializing .NET objects into JSON objects.
One feature that I find useful is its ability to rename attributes in my classes. For example, if I have a class named "SocialSecurityNumber" in my C# class and the client consuming my JSON object expects that same property to be named "ssn", I can make this transformation declaratively by adding the JsonProperty attribute to the class property, as shown in Listing 1.
For projects with many objects and many properties, this can be a tedious task. Fortunately, I recently learned a shortcut.
ASP.NET contains a Formatters class that controls how items are formatted and Newtonsoft.Json can tap into this. The following code, when run at the start of your application, converts all properties to Camel-Case as you transform them to JSON.
I added this code to the Register method of the WebApiConfig class in my ASP.NET MVC project, so that it is run when the application starts up, before any serialization is done.
Another useful setting is to add carriage returns and line feeds to the JSON that is created. This has the disadvantage of making your JSON slightly larger; but it makes it much easier for human beings to read, which can be very useful during debugging. This is accomplished with the following line:
The full listing in the Register() method is shown below:
Using the tools in the Newtonsoft.Json library, we can easily adhere to the conventional naming conventions of whatever platform in which our data is used.