C# Newtonsoft Json.NET
last modified October 16, 2026
In this article we show how to work with JSON data using the 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 JSON framework for .NET. For many
years, it was the standard way to work with JSON in .NET. Since .NET Core 3.0,
the standard library includes the faster System.Text.Json, which
is recommended for new code. Json.NET is still widely used in existing projects
and offers some features that System.Text.Json lacks, such as the
flexible LINQ to JSON API.
$ dotnet add package Newtonsoft.Json
We add the package to the project. The examples were tested with Json.NET 13.0.4.
JsonConvert provides methods for converting between .NET types and
JSON. 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.
using Newtonsoft.Json;
var p = new Product("Product A", new DateTime(2021, 12, 28), ["small", "medium"]);
var json = JsonConvert.SerializeObject(p);
Console.WriteLine(json);
record Product(string Name, DateTime Created, string[] Sizes);
A product record is transformed into a JSON string. The date is written in the ISO 8601 format.
$ dotnet run
{"Name":"Product A","Created":"2021-12-28T00:00:00","Sizes":["small","medium"]}
Json.NET deserialize into object
The next example deserializes a JSON string back into a .NET type.
using Newtonsoft.Json;
var json = """{"Name":"Product A","Created":"2021-12-28T00:00:00","Sizes":["small","medium"]}""";
Product? p = JsonConvert.DeserializeObject<Product>(json);
Console.WriteLine(p?.Name);
Console.WriteLine(p?.Created.ToShortDateString());
Console.WriteLine(string.Join(", ", p?.Sizes ?? []));
record Product(string Name, DateTime Created, string[] Sizes);
We transform the JSON string back into the record type. The JSON is written as a raw string literal, so we do not have to escape the quotes.
Product? p = JsonConvert.DeserializeObject<Product>(json);
Inside the angle brackets, we specify the requested .NET type. The method
returns null for the JSON null literal; therefore,
the result is nullable. Json.NET matches the property names case-insensitively
and uses the constructor of the record.
$ dotnet run Product A 12/28/2021 small, medium
Json.NET serialize list
In the next example, we serialize lists.
using Newtonsoft.Json;
List<string> words = ["war", "water", "cup", "forest", "falcon", "snow"];
string data = JsonConvert.SerializeObject(words);
Console.WriteLine(data);
List<User> users =
[
new("John Doe", "gardener"),
new("Roger Roe", "driver"),
new("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 a list of users into JSON arrays.
$ dotnet run
["war","water","cup","forest","falcon","snow"]
[{"Name":"John Doe","Occupation":"gardener"},{"Name":"Roger Roe","Occupation":"driver"},{"Name":"Lucia Novak","Occupation":"teacher"}]
Json.NET deserialize list
The next example deserializes JSON arrays into lists.
using Newtonsoft.Json;
var json1 = """["war","water","cup","forest","falcon","snow"]""";
var json2 = """
[{"Name":"John Doe","Occupation":"gardener"},
{"Name":"Roger Roe","Occupation":"driver"},
{"Name":"Lucia Novak","Occupation":"teacher"}]
""";
List<string> words = JsonConvert.DeserializeObject<List<string>>(json1) ?? [];
Console.WriteLine(string.Join(',', words));
List<User> users = JsonConvert.DeserializeObject<List<User>>(json2) ?? [];
users.ForEach(Console.WriteLine);
record User(string Name, string Occupation);
The program transforms the two JSON strings back into a list of strings and a
list of users. If the result is null, we use an empty list.
$ dotnet run
war,water,cup,forest,falcon,snow
User { Name = John Doe, Occupation = gardener }
User { Name = Roger Roe, Occupation = driver }
User { Name = Lucia Novak, Occupation = teacher }
Json.NET serializer settings
The JsonSerializerSettings class customizes the serialization.
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
var settings = new JsonSerializerSettings
{
Formatting = Formatting.Indented,
ContractResolver = new CamelCasePropertyNamesContractResolver(),
NullValueHandling = NullValueHandling.Ignore
};
List<User> users =
[
new("John Doe", "gardener", "john@example.com"),
new("Roger Roe", "driver", null)
];
string data = JsonConvert.SerializeObject(users, settings);
Console.WriteLine(data);
record User(string Name, string Occupation, string? Email);
We produce indented JSON with camel-case property names and leave out the
properties whose value is null.
ContractResolver = new CamelCasePropertyNamesContractResolver(),
The contract resolver changes the property names from Name to
name, which is the usual style in JavaScript and web APIs.
NullValueHandling = NullValueHandling.Ignore
The second user has no email; the property is omitted from the output.
$ dotnet run
[
{
"name": "John Doe",
"occupation": "gardener",
"email": "john@example.com"
},
{
"name": "Roger Roe",
"occupation": "driver"
}
]
Json.NET attributes
Attributes control the serialization of individual members. The
JsonProperty attribute sets the name of a property in JSON and the
JsonIgnore attribute excludes a property.
using Newtonsoft.Json;
var user = new User { Id = 1, FirstName = "John", LastName = "Doe", Password = "s3cr3t" };
string json = JsonConvert.SerializeObject(user);
Console.WriteLine(json);
var user2 = JsonConvert.DeserializeObject<User>("""{"id":2,"first_name":"Lucy","last_name":"Novak"}""");
Console.WriteLine($"{user2?.FirstName} {user2?.LastName}");
class User
{
[JsonProperty("id")]
public int Id { get; set; }
[JsonProperty("first_name")]
public string FirstName { get; set; } = "";
[JsonProperty("last_name")]
public string LastName { get; set; } = "";
[JsonIgnore]
public string Password { get; set; } = "";
}
The JSON uses snake-case names. The password is never written to JSON.
$ dotnet run
{"id":1,"first_name":"John","last_name":"Doe"}
Lucy Novak
Json.NET LINQ to JSON
LINQ to JSON is an API for working with JSON without defining .NET types. The
JObject, JArray, and JToken classes
represent the parts of a JSON document. We can read and modify them
dynamically.
using Newtonsoft.Json.Linq;
var json = """
{
"name": "John Doe",
"address": { "city": "Bratislava", "zip": "81101" },
"languages": ["C#", "Python", "Go"]
}
""";
JObject obj = JObject.Parse(json);
Console.WriteLine(obj["name"]);
Console.WriteLine(obj["address"]?["city"]);
Console.WriteLine(obj.SelectToken("languages[1]"));
Console.WriteLine(obj["languages"]?.Count());
obj["age"] = 34;
((JArray) obj["languages"]!).Add("Rust");
Console.WriteLine(obj.ToString(Newtonsoft.Json.Formatting.None));
We parse a JSON document, read some of its values, and modify it.
Console.WriteLine(obj["address"]?["city"]);
The indexer returns a JToken, or null if the
property does not exist. We navigate nested objects with chained indexers.
Console.WriteLine(obj.SelectToken("languages[1]"));
The SelectToken method takes a JSONPath expression.
obj["age"] = 34;
((JArray) obj["languages"]!).Add("Rust");
We add a new property and a new array element.
$ dotnet run
John Doe
Bratislava
Python
3
{"name":"John Doe","address":{"city":"Bratislava","zip":"81101"},"languages":["C#","Python","Go","Rust"],"age":34}
Json.NET read JSON data from web
Next we use HttpClient to create a GET request and process the
JSON output. We use the JSONPlaceholder service, a free fake REST API for
testing.
using Newtonsoft.Json;
using var client = new HttpClient();
var url = "https://jsonplaceholder.typicode.com/users";
var json = await client.GetStringAsync(url);
List<User> users = JsonConvert.DeserializeObject<List<User>>(json) ?? [];
foreach (var user in users.Take(5))
{
Console.WriteLine(user);
}
record Address(string City, string ZipCode);
record User(int Id, string Name, string Email, Address Address);
We read a JSON array of users from a web resource and turn it into a list of records.
record Address(string City, string ZipCode); record User(int Id, string Name, string Email, Address Address);
The records contain only the properties we need; the other properties of the
JSON objects are ignored. The nested address object is mapped to
the Address record.
$ dotnet run
User { Id = 1, Name = Leanne Graham, Email = Sincere@april.biz, Address = Address { City = Gwenborough, ZipCode = 92998-3874 } }
User { Id = 2, Name = Ervin Howell, Email = Shanna@melissa.tv, Address = Address { City = Wisokyburgh, ZipCode = 90566-7771 } }
User { Id = 3, Name = Clementine Bauch, Email = Nathan@yesenia.net, Address = Address { City = McKenziehaven, ZipCode = 59590-4157 } }
User { Id = 4, Name = Patricia Lebsack, Email = Julianne.OConner@kory.org, Address = Address { City = South Elvis, ZipCode = 53919-4257 } }
User { Id = 5, Name = Chelsey Dietrich, Email = Lucio_Hettinger@annie.ca, Address = Address { City = Roscoeview, ZipCode = 33263 } }
Source
In this article we have worked with JSON data in C# using Newtonsoft
Json.NET.
Author
List all C# tutorials.