JSON and .NET

Quick History Lesson in XML

Before JSON became popular, XML (eXtensible Markup Language) was the primary format for data interchange on the web. XML is a markup language that uses tags to define elements and attributes, which makes it highly descriptive but often verbose and complex.

<person id="123" status="active">
    <name>
        <first>John</first>
        <last>Doe</last>
    </name>
    <age unit="years">30</age>
    <contact>
        <email type="personal">john.doe@example.com</email>
        <phone type="mobile">(555) 123-4567</phone>
    </contact>
    <address>
        <street>123 Main St</street>
        <city>Anytown</city>
        <country code="US">United States</country>
    </address>
</person>

JSON was the solution to this problem, and has become the defacto standard format for data interchange on the web.

Unveiling JSON

What is JSON?

JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy for humans to read and write, and easy for machines to parse and generate. It is used to represent structured data and is commonly used in web applications for exchanging data between clients and servers.

{
    "id": "123",
    "status": "active",
    "firstName": "John",
    "lastName": "Doe",
    "age": 30,
    "contact": {
        "email": {
            "type": "personal",
            "address": "john.doe@example.com"
        },
        "phone": {
            "type": "mobile",
            "number": "(555) 123-4567"
        }
    },
    "address": {
        "street": "123 Main St",
        "city": "Anytown",
        "country": {
            "code": "US",
            "name": "United States"
        }
    }
}

There are two common libraries for working with JSON in .NET:

  1. Newtonsoft.Json: A popular and widely used library for handling JSON in .NET applications. Has been around for a long long time and therefore is in a lot of existing applications.
  2. System.Text.Json: A newer library introduced in .NET Core 3.0 that focuses on performance improvements, accuracy, and security.

Newtonsoft.Json

Overview

  • Older but Very Common: Newtonsoft.Json, also known as Json.NET, is a popular and widely used library for handling JSON in .NET applications.
  • Relaxed and Forgiving: It's known for its ability to handle various JSON formats and scenarios, including some that might be less strictly defined (like JSON with comments).

Key Features

  • JsonConvert: A class that provides static methods for converting JSON to and from .NET objects.

var employee = new Employee
{
    Id = 1,
    FirstName = "John",
    LastName = "Doe",
    Age = 30
};

var json = JsonConvert.SerializeObject(employee);

var johnReborn = JsonConvert.DeserializeObject<Employee>(json);

System.Text.Json

Overview

  • Emphasizes Speed, Accuracy, Exactness, Security: System.Text.Json is a newer library introduced in .NET Core 3.0. It focuses on performance improvements, accuracy, and security.

Key Features

  • JsonSerializer: A class that provides methods for serializing and deserializing JSON data.
var employee = new Employee
{
    Id = 1,
    FirstName = "John",
    LastName = "Doe",
    Age = 30
};

var json = JsonSerializer.Serialize(employee);
var johnReborn = JsonSerializer.Deserialize<Employee>(json);

Comparing Newtonsoft.Json and System.Text.Json

JsonConvert vs. JsonSerializer

  • JsonConvert: Comes from Newtonsoft.Json and provides a flexible API for JSON operations.
  • JsonSerializer: Comes from System.Text.Json and offers high-performance serialization and deserialization.

Weirdness with JSON Converters

  • Enums: Enums in JSON are typically serialized as their base types (e.g., integers) unless explicitly configured to be serialized differently.

🌶️🌶️🌶️ We live in an integrated world, so please configure your JSON serializers to send enums as strings.

Which Should You Use?

  • Greenfield Projects: Use System.Text.Json for new projects to leverage its performance and security benefits.
  • Existing Projects: Newtonsoft.Json is still fine for ongoing projects, but consider migrating to System.Text.Json as you update your applications. Problem is, most of the time there are just bigger fish to fry.
  • Avoid Mixing Libraries: To prevent developer confusion and integration issues, it’s best not to mix Newtonsoft.Json and System.Text.Json in the same project if you can avoid it.

🌶️🌶️🌶️ If the project is using Newtonsoft.Json already, avoid introducing System.Text.Json unless you really really need the extra performance.