Reading and Writing JSON

Json.NET

Json.NET - Quick Starts & API Documentation Reading and Writing JSON

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

JsonTextReader and JsonTextWriter

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, indention character, indent count and quote character.

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
 
using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
  jsonWriter.Formatting = Formatting.Indented;
 
  jsonWriter.WriteStartObject();
  jsonWriter.WritePropertyName("CPU");
  jsonWriter.WriteValue("Intel");
  jsonWriter.WritePropertyName("PSU");
  jsonWriter.WriteValue("500W");
  jsonWriter.WritePropertyName("Drives");
  jsonWriter.WriteStartArray();
  jsonWriter.WriteValue("DVD read/writer");
  jsonWriter.WriteComment("(broken)");
  jsonWriter.WriteValue("500 gigabyte hard drive");
  jsonWriter.WriteValue("200 gigabype hard drive");
  jsonWriter.WriteEnd();
  jsonWriter.WriteEndObject();
}
 
// {
//   "CPU": "Intel",
//   "PSU": "500W",
//   "Drives": [
//     "DVD read/writer"
//     /*(broken)*/,
//     "500 gigabyte hard drive",
//     "200 gigabype hard drive"
//   ]
// }

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.

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));
 
Console.WriteLine(p.Name);
// John Smith