Click or drag to resize

Basic Reading and Writing JSON


To manually read and write JSON, Json.NET provides the JsonReader and JsonWriter classes.

JsonTextReader and JsonTextWriter
Note Note

JsonReader and JsonWriter are low-level classes and are primarily for internal use by Json.NET. To quickly work with JSON, either the serializer - Serializing and Deserializing JSON - or using LINQ to JSON is recommended.

JsonTextReader and JsonTextWriter are used to read and write JSON text. The JsonTextWriter has a number of settings on it to control how JSON is formatted when it is written. These options include formatting, indentation character, indent count, and quote character.

Writing JSON with JsonTextWriter
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

using (JsonWriter writer = new JsonTextWriter(sw))
    writer.Formatting = Formatting.Indented;

    writer.WriteValue("DVD read/writer");
    writer.WriteValue("500 gigabyte hard drive");
    writer.WriteValue("200 gigabyte hard drive");

// {
//   "CPU": "Intel",
//   "PSU": "500W",
//   "Drives": [
//     "DVD read/writer"
//     /*(broken)*/,
//     "500 gigabyte hard drive",
//     "200 gigabyte hard drive"
//   ]
// }

JsonTextReader has settings on it for reading different date formats, time zones, and the cultures when reading text values.

Reading JSON with JsonTextReader
string json = @"{
   'CPU': 'Intel',
   'PSU': '500W',
   'Drives': [
     'DVD read/writer'
     '500 gigabyte hard drive',
     '200 gigabyte hard drive'

JsonTextReader reader = new JsonTextReader(new StringReader(json));
while (reader.Read())
    if (reader.Value != null)
        Console.WriteLine("Token: {0}, Value: {1}", reader.TokenType, reader.Value);
        Console.WriteLine("Token: {0}", reader.TokenType);

// Token: StartObject
// Token: PropertyName, Value: CPU
// Token: String, Value: Intel
// Token: PropertyName, Value: PSU
// Token: String, Value: 500W
// Token: PropertyName, Value: Drives
// Token: StartArray
// Token: String, Value: DVD read/writer
// Token: Comment, Value: (broken)
// Token: String, Value: 500 gigabyte hard drive
// Token: String, Value: 200 gigabyte hard drive
// Token: EndArray
// Token: EndObject
JTokenReader and JTokenWriter

JTokenReader and JTokenWriter read and write LINQ to JSON objects. They are located in the Newtonsoft.Json.Linq namespace. These objects allow you to use LINQ to JSON objects with objects that read and write JSON, such as the JsonSerializer. For example you can deserialize from a LINQ to JSON object into a regular .NET object and vice versa.

Deserializing with JTokenReader
JObject o = new JObject(
    new JProperty("Name", "John Smith"),
    new JProperty("BirthDate", new DateTime(1983, 3, 20))

JsonSerializer serializer = new JsonSerializer();
Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));

// John Smith
See Also