Serialization (2) - JSON Serialization

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file. Its main purpose is to save the state of an object in order to be able to recreate it when needed. The reverse process is called deserialization.

A - Introduction

This article is about Newtonsoft JSON deserializing, and its 

The Newtonsoft.JSON namespace provides classes that are used to implement the core services of the framework. It provides methods for converting between .NET types and JSON types.

System.Text.Json is a new JSON library for .NET introduced by Microsoft with different design goals --- high performance --- from its predecessor, Newtonsoft.Json. 

This is the structure of this article,

  • A - Introduction
  • B - Newtonsoft Json Serialization
  • C - Microsoft System.Text.Json
    • C - 1: History
    • C - 2: Performance Comparison
    • C - 3: Differences between System.Text.Json and Newtonsoft Json

B - Newtonsoft JSON Serialization

B - 1: History [ref] --- James Newton, the author of Newtonsoft

Json.NET grew out of projects I was working on in late 2005 involving JavaScript, AJAX, and .NET. At the time there were no libraries for working with JavaScript in .NET, so I made my own.

Starting out as a couple of static methods for escaping JavaScript strings, Json.NET evolved as features were added. To add support for reading JSON a major refactor was required, and Json.NET was split into the three major classes it still uses today: JsonReader, JsonWriter and JsonSerializer.

Json.NET was first released in June 2006. Since then Json.NET has been downloaded hundreds of thousands of times by developers from around the world. It is used in many major open source projects, including: Mono, an open source implementation of the .NET framework; RavenDB, a JSON based document database; ASP.NET SignalR, an async library for building real-time, multi-user interactive web applications; and ASP.NET Core, Microsoft's web app and service framework.

B - 2: Benefits and Features [ref]

  • Flexible JSON serializer for converting between .NET objects and JSON
  • LINQ to JSON for manually reading and writing JSON
  • High performance: faster than .NET's built-in JSON serializers
  • Write indented, easy-to-read JSON
  • Convert JSON to and from XML
  • Supports .NET Standard 2.0, .NET 2, .NET 3.5, .NET 4, .NET 4.5, Silverlight, Windows Phone and Windows 8 Store

The JSON serializer in Json.NET is a good choice when the JSON you are reading or writing maps closely to a .NET class.

LINQ to JSON is good for situations where you are only interested in getting values from JSON, you don't have a class to serialize or deserialize to, or the JSON is radically different from your class and you need to manually read and write from your objects.

B - 3: Serializing and Deserializing JSON by Newtonsoft, Samples

JsonConvert:

For simple scenarios where you want to convert to and from a JSON string, the  SerializeObject()  and DeserializeObject() methods on JsonConvert provide an easy-to-use wrapper over JsonSerializer.

Serializing and Deserializing JSON with JsonConvert

Product product = new Product();

product.Name = "Apple";
product.ExpiryDate = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };

string output = JsonConvert.SerializeObject(product);
//{
//  "Name": "Apple",
//  "ExpiryDate": "2008-12-28T00:00:00",
//  "Price": 3.99,
//  "Sizes": [
//    "Small",
//    "Medium",
//    "Large"
//  ]
//}

Product deserializedProduct = JsonConvert.DeserializeObject<Product>(output);

SerializeObject and DeserializeObject both have overloads that take a JsonSerializerSettings object. JsonSerializerSettings lets you use many of the JsonSerializer settings listed below while still using the simple serialization methods.

JsonSerializer

For more control over how an object is serialized, the JsonSerializer can be used directly. The JsonSerializer is able to read and write JSON text directly to a stream via JsonTextReader and JsonTextWriter. Other kinds of JsonWriters can also be used, such as JTokenReader/JTokenWriter, to convert your object to and from LINQ to JSON objects, or BsonReader/BsonWriter, to convert to and from BSON.

Serializing JSON to a Stream with JsonSerializer

Product product = new Product();
product.ExpiryDate = new DateTime(2008, 12, 28);

JsonSerializer serializer = new JsonSerializer();
serializer.Converters.Add(new JavaScriptDateTimeConverter());
serializer.NullValueHandling = NullValueHandling.Ignore;

using (StreamWriter sw = new StreamWriter(@"c:\json.txt"))
using (JsonWriter writer = new JsonTextWriter(sw))
{
    serializer.Serialize(writer, product);
    // {"ExpiryDate":new Date(1230375600000),"Price":0}
}

JsonSerializer has a number of properties on it to customize how it serializes JSON. These can also be used with the methods on JsonConvert via the JsonSerializerSettings overloads.

C - Microsoft System.Text.Json

C - 1: History [ref]

Microsoft shipped a new namespace called System.Text.Json with .NET Core 3.0. This one is integrated with .NET Core 3.0, so you no longer need to install a nuget package for Newtonsoft Json.

It's important to understand the reasoning behind writing a whole new JSON library when we already have Newtonsoft.Json. System.Text.Json was designed first and foremost with high performance in mind - the .NET team (which includes James Newton-King, the guy who wrote Newtonsoft.Json) found they couldn't refactor Newtonsoft.Json to meet some of these goals without making breaking changes to existing code.

Note
For .Net, we can say, we use(d) Newtonsoft Json for .Net Framework, while we should and could use the new lib, System.Text.Json for .Net Core, at least after 3.0.

C - 2: Performance Comparison  [ref]

System.Text.Json library is focused on high performance.

As seen above, System.Text.Json is much faster than Newtonsoft.Json.

C - 3: Differences between System.Text.Json and Newtonsoft Json

Can be seen from

Reference