Introduction

1. Introduction to Newtonsoft.Json

Newtonsoft.Json (commonly known as Json.NET) is an open‑source JSON serialization/deserialization library for the .NET ecosystem

  • First release Json.NET 1.0.1 launched in 2006, major versions have reached 10+
  • Originally compatible with .NET 2.0, supports nearly all .NET frameworks (Framework/.NET Core/.NET 5+)
  • Assembly: Newtonsoft.Json.dll, install via NuGet
  • Source code was hosted on CodePlex in early days, now migrated to GitHub, widely adopted in enterprise‑level projects

2. What is JSON

JSON(JavaScript Object Notation)

  • Lightweight, language‑agnostic text‑based data‑exchange format, not exclusive to JavaScript
  • Core structure: key‑value pair key:value; supports nested objects {} and arrays []
{"webname":"FoxDevelop","website":"foxdevelop.com","age":4,"students":[{"name":"tom"},{"name":"bill"}]}Code language: C# (cs)

II. Define Entity Classes (Map to JSON Structure)

Person.cs (Student Object)
namespace NewtonsoftDemo
{
    public class Person
    {
        public string name { set; get; }
    }
}Code language: C# (cs)
WebInfo.cs (Root Object)
namespace NewtonsoftDemo
{
    public class WebInfo
    {
        public string webname { set; get; }
        public string website { set; get; }
        public int age { set; get; }
        public Person[] students { set; get; }
    }
}Code language: C# (cs)

Example‑Serialize Object to JSON

protected void Page_Load(object sender, EventArgs e)
{
    // 1. Instantiate entity and assign values
    WebInfo webInfo = new WebInfo();
    webInfo.age = 4;
    webInfo.webname = "FoxDevelop";
    webInfo.website = "foxdevelop.com";
    webInfo.students = new Person[] 
    { 
        new Person { name = "TOM" },
        new Person { name = "JACK" } 
    };

    // 2. Low‑level Newtonsoft.Json: serialize with JsonWriter
    StringWriter sw = new StringWriter();
    JsonWriter writer = new JsonWriter(sw);
    new JsonSerializer().Serialize(writer, webInfo);
    string json = sw.GetStringBuilder().ToString();
}Code language: C# (cs)

Simplified Code for Daily Use

Newtonsoft.Json provides static helper methods to avoid manually creating JsonWriter:

// One‑line serialization, widely used in development
string json = JsonConvert.SerializeObject(webInfo);Code language: C# (cs)

Output JSON Result

{
  "webname": "FoxDevelop",
  "website": "foxdevelop.com",
  "age": "4",
  "students": [
    {"name":"TOM"},
    {"name":"JACK"}
  ]
}Code language: C# (cs)

Others

  • System.Text.Json: Microsoft built‑in JSON library starting from .NET Core 3.0; Newtonsoft.Json is still popular for legacy .NET Framework projects
  • Features: property aliasing, field ignoring, date formatting, circular reference handling and other advanced capabilities

Introduction

Leave a Reply

Your email address will not be published. Required fields are marked *