Json.NET is a popular high-performance JSON framework for .NET available via Nuget as Newtonsoft.Json
JSON (JavaScript Object Notation) is widely used and I find it easier to read than XML (eXtensible Markup Language.) I doubt XML is going anywhere and the differences will be opinion based so I have no intention to insinuate JSON is better.
JSON is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999.
Modern Web API projects can be configured to automatically return JSON with the JsonFormatter class however there are plenty legacy systems that will still follow the below structure so it’s good to understand them anyway.
In some cases your class instances need to be persisted to a log file or database, the simplest way to do this is with the JsonConvert class from Json.Net and it is faster than the JavaScriptSerializer class normally used in older .ASMX files.
.ASMX is an abbreviation for Active Server Method File, a file with the ASMX file extension is an ASP.NET Web Service Source file.
The below is a pre Web API example of web a web service called ‘AjaxServer.asmx’ that uses JavaScriptSerializer
1 | using Newtonsoft.Json; |
This can then be consumed from the client side. The simplest way is with jQuery’s $.ajax to post to the service and $.parseJSON to de-serialize the response.
NOTE: As of jQuery 3.0, $.parseJSON is deprecated. To parse JSON strings use the native JSON.parse method instead.
1 | var obj = jQuery.parseJSON( '{ "name": "John" }' ); |
Json.NET
The json object instance from the ‘AjaxServer.asmx’ example above can then be replaced with JsonConvert.SerializeObject(list)
JsonConvert.DeserializeAnonymousType is also very helpful for unit testing Web API projects.
The examples from newtonsoft.com are very simple and clearly show how to Serialize and Deserialize json notation.
1 | //******* Serialize JSON |
Some humour instead of closing thoughts as I really enjoyed ‘The Transporter’ movies :D