ZetCode

C# Newtonsoft Json.NET

last modified July 5, 2023

C# Json.NET tutorial shows how to work with JSON data using Newtonsoft Json.NET library.

JSON

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easily read and written by humans and parsed and generated by machines. The application/json is the official Internet media type for JSON. The JSON filename extension is .json.

Newtonsoft Json.NET is a popular high-performance JSON framework for .NET.

In this article we work with Newtonsoft Json.NET library. In the standard library, we can alternatively use System.Text.Json.

JsonConvert provides methods for converting between .NET types and JSON types. JsonConvert.SerializeObject serializes the specified object to a JSON string. JsonConvert.DeserializeObject deserializes the JSON to a .NET object.

Json.NET serialize object

In the following example, we serialize an object to a JSON string.

Program.cs
using Newtonsoft.Json;

var p = new Product("Product A", new DateTime(2021, 12, 28),
    new string[] { "small" });

var json = JsonConvert.SerializeObject(p);
Console.WriteLine(json);

record Product(string Name, DateTime Created, string[] Sizes);

A product record is transformed into s JSON strring.

$ dotnet run
{"Name":"Product A","Created":"2021-12-28T00:00:00","Sizes":["small"]}

Json.NET deserialize into object

The next example serializes the generated JSON string back into the .NET type.

Program.cs
using Newtonsoft.Json;

var json = @"{""Name"":""Product A"",""Created"":""2021-12-28T00:00:00"",""Sizes"":[""small""]}";

Product? p = JsonConvert.DeserializeObject<Product>(json);
Console.WriteLine(p);

record Product(string Name, DateTime Created, string[] Sizes);

We transform the JSON string back into the record type.

Product? p = JsonConvert.DeserializeObject<Product>(json);

Inside the angle brackets, we specify the requested .NET type.

$ dotnet run
Product { Name = Product A, Created = 12/28/2021 12:00:00 AM, Sizes = System.String[] }

Json.NET serialize list

In the next example, we serialize a list.

Program.cs
using Newtonsoft.Json;

var words = new List<string> { "war", "water", "cup",
    "forest", "falcon", "snow", "chair", "book" };

string data = JsonConvert.SerializeObject(words);
Console.WriteLine(data);

var users = new List<User> {
    new User("John Doe", "gardener"),
    new User("Roger Roe", "driver"),
    new User("Lucia Novak", "teacher")
};

string data2 = JsonConvert.SerializeObject(users);
Console.WriteLine(data2);

record User(string Name, string Occupation);

The program turns a list of strings and user objects into JSON strings using JsonConvert.SerializeObject.

$ dotnet run
["war","water","cup","forest","falcon","snow","chair","book"]
[{"Name":"John Doe","Occupation":"gardener"},{"Name":"Roger Roe","Occupation":"driver"},
    {"Name":"Lucia Novak","Occupation":"teacher"}]

Json.NET deserialize list

The next example deserializes lists.

Program.cs
using Newtonsoft.Json;

string json1 = @"[""war"",""water"",""cup"",""forest"",""falcon"",""snow"",""chair"",""book""]";
string json2 = @"[{""Name"":""John Doe"",""Occupation"":""gardener""},{""Name"":""Roger Roe"",""Occupation"":""driver""},
    {""Name"":""Lucia Novak"",""Occupation"":""teacher""}]";

List<string>? words = JsonConvert.DeserializeObject<List<string>>(json1);

if (words != null)
{
    Console.WriteLine(string.Join(',', words));
}

List<User>? users = JsonConvert.DeserializeObject<List<User>>(json2);

if (users != null)
{
    Console.WriteLine(string.Join(',', users));
}

record User(string Name, string Occupation);

The program transforms the two JSON strings back into a list of strings and a list of user objects.

$ dotnet run
war,water,cup,forest,falcon,snow,chair,book
User { Name = John Doe, Occupation = gardener },User { Name = Roger Roe, Occupation = driver },User { Name = Lucia Novak, Occupation = teacher }

Json.NET pretty print

The following example prettifies the JSON output.

Program.cs
using Newtonsoft.Json;

var settings = new JsonSerializerSettings
{
    Formatting = Newtonsoft.Json.Formatting.Indented
};

var users = new List<User> {
    new User("John Doe", "gardener"),
    new User("Roger Roe", "driver"),
    new User("Lucia Novak", "teacher")
};

string data = JsonConvert.SerializeObject(users, settings);
Console.WriteLine(data);

record User(string Name, string Occupation);

We use JsonSerializerSettings to modify the JSON output.

var settings = new JsonSerializerSettings
{
    Formatting = Newtonsoft.Json.Formatting.Indented
};

We set the Newtonsoft.Json.Formatting.Indented for a nicer output.

$ dotnet run
[
    {
    "Name": "John Doe",
    "Occupation": "gardener"
    },
    {
    "Name": "Roger Roe",
    "Occupation": "driver"
    },
    {
    "Name": "Lucia Novak",
    "Occupation": "teacher"
    }
]

Json.NET read JSON data from web

Next we use HttpClient to create a GET request and process the JSON output.

Program.cs
using Newtonsoft.Json;

using var client = new HttpClient();

var url = "http://webcode.me/users.json";

var res = await client.GetAsync(url);
var json = await res.Content.ReadAsStringAsync();

Users? data = JsonConvert.DeserializeObject<Users>(json);

if (data != null)
{
    foreach (var user in data.users)
    {
        Console.WriteLine(user);
    }
}

class Users
{
    public List<User> users { get; set; } = new();
}

class User
{
    [JsonPropertyAttribute("id")]
    public int Id { get; set; }

    [JsonPropertyAttribute("first_name")]
    public string FirstName { get; set; } = string.Empty;

    [JsonPropertyAttribute("last_name")]
    public string LastName { get; set; } = string.Empty;

    [JsonPropertyAttribute("email")]
    public string Email { get; set; } = string.Empty;

    public override string ToString()
    {
        return $"User {{ {Id}| {FirstName} {LastName}| {Email} }}";
    }
}

We read a JSON string from a web resource and turn it into a list of objects.

var res = await client.GetAsync(url);

We create a GET request to the specified resource.

var json = await res.Content.ReadAsStringAsync();

From the response content, we get the JSON string.

Users? data = JsonConvert.DeserializeObject<Users>(json);

We deserialize the JSON string into a list of users.

[JsonPropertyAttribute("first_name")]
public string FirstName { get; set; } = string.Empty;

The JsonPropertyAttribute instructs the JsonSerializer to always serialize the member with the specified name.

$ dotnet run
User { 1| Robert Schwartz| rob23@gmail.com }
User { 2| Lucy Ballmer| lucyb56@gmail.com }
User { 3| Anna Smith| annasmith23@gmail.com }
User { 4| Robert Brown| bobbrown432@yahoo.com }
User { 5| Roger Bacon| rogerbacon12@yahoo.com }

Source

Json.NET documentation

In this article we have worked with JSON data in C# using Newtonsoft Json.NET.

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials.