Json.NET (.NET library)

Json.NET

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Web.Services;

namespace JsonNetWebAppDemo
{
/// <summary>
/// Summary description for AjaxServer
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class AjaxServer : System.Web.Services.WebService
{
[WebMethod(EnableSession = true)]
public string DoSomething(string param1, string param2)
{
if (param1 == "" && param2 == "")
return "[]";

var list = new List<string>();
list.Add("some string value");

if (Session["someSessionValue"] != null)
list.Add(Session["someSessionValue"].ToString());

//slower built in 'JavaScriptSerializer'
var json = new JavaScriptSerializer().Serialize(list);
return json;

//faster 'JsonConvert'
//var json2 = JsonConvert.SerializeObject(list);
//return json2;
}
}
}

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
2
3
4
5
var obj = jQuery.parseJSON( '{ "name": "John" }' );
alert( obj.name === "John" );

var obj2 = JSON.parse( '{ "name": "John" }' );
alert( obj2.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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//******* Serialize JSON

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Sizes = new string[] { "Small" };

string json = JsonConvert.SerializeObject(product);
// {
// "Name": "Apple",
// "Expiry": "2008-12-28T00:00:00",
// "Sizes": [
// "Small"
// ]
// }


//******* Deserialize JSON
string json = @"{
'Name': 'Bad Boys',
'ReleaseDate': '1995-4-7T00:00:00',
'Genres': [
'Action',
'Comedy'
]
}";

Movie m = JsonConvert.DeserializeObject<Movie>(json);

string name = m.Name;
// Bad Boys

Some humour instead of closing thoughts as I really enjoyed ‘The Transporter’ movies :D

JSON Statham :D

References