liveBook · Manning

JSON

As explained in .NET in Action, Second Edition

JSON is a text-based data-interchange format that represents structured values such as objects, arrays, strings, numbers, booleans, and null.

JSON is a text format for structured data. A document can contain an array of objects, such as records with numeric IDs and string properties. In .NET, System.Text.Json provides two practical ways to work with it: inspect and write elements directly, or map a known schema to C# objects with a serializer. section 4.2 section 4.2.1 section 4.2.3

Use a Stream to read a JSON file rather than treating it as independent lines. JsonDocument.Parse reads the input stream; RootElement.EnumerateArray visits its elements, and GetProperty retrieves values for filtering. This approach is useful when selecting or copying parts of a document without defining a C# type for every object. section 4.2.1 section 4.2.2

Listing 4.22 Using Utf8JsonWriter to write well-formed JSON
static void FindWithJsonDom(
  Stream inStream,
  Stream outStream,
  string category)
{
  var writerOptions = new JsonWriterOptions         #1
    { Indented = true };                            #2
  using var writer = new Utf8JsonWriter(outStream,  #3
    writerOptions);
  writer.WriteStartArray();                         #4
  
  using var jsonDoc =
    JsonDocument.Parse(inStream);                   #5
  foreach (var jokeElement in jsonDoc
    .RootElement.EnumerateArray())
  {
    string? type = jokeElement
      .GetProperty("type")
      .GetString();
    if (string.Equals(category, type,
      StringComparison.OrdinalIgnoreCase))
    {
      jokeElement.WriteTo(writer);                  #6
    }
  }
  
  writer.WriteEndArray();                           #7
}

The category filter copies matching elements into a new array. Utf8JsonWriter supplies the array boundaries, separators, and optional indentation; writing raw element text alone would not produce valid JSON. section 4.2.2

When the schema is known, define a matching C# record and deserialize the stream with JsonSerializer. Filter the resulting objects with LINQ, then serialize them to an output stream. A projection can limit output to selected properties and give those properties the desired names. Case-insensitive reading helps when JSON names differ from C# names only by capitalization; JsonPropertyName handles other name differences. section 4.2.3 section 4.3

Listing 4.26 Reading and writing JSON with JsonSerializer
static void FindWithSerialization(                       #1
  Stream inStream,
  Stream outStream,
  string category
)
{
  var serialOptions = new JsonSerializerOptions          #2
    { WriteIndented = true,                              #3
      PropertyNameCaseInsensitive = true };              #4
  var jokes = JsonSerializer.Deserialize<Joke[]>(        #5
    inStream,                                            #6
    serialOptions);                                      #7
  JsonSerializer.Serialize(                              #8
    outStream,
    jokes?.Where(j => string.Equals(                     #9
      category, j.Type,
      StringComparison.OrdinalIgnoreCase))
      .ToArray(),                                        #10
    serialOptions);                                      #11
}

This implementation deserializes an array of records, filters it by category, and serializes the result. Its options enable case-insensitive property matching and indented output. section 4.2.3

JSON from an HTTP response

A comic-search application obtains a JSON response stream with HttpClient and deserializes it into a Comic record. JsonPropertyName maps names such as safe_title to a differently named C# property; JsonIgnore excludes a computed date. The nullable result also requires a caller to account for the absence of a comic. section 4.3

How .NET in Action, Second Edition covers it

How deep it goes
Works through stream-based DOM reading, valid output, and typed serialization, without developing a full JSON grammar.
Examples
Builds a category-filtered joke file and a comic-metadata search using JSON from an HTTP API.
What it assumes
Assumes familiarity with C# application code while introducing streams as the input and output abstraction for JSON.
What you can do after
Build it from scratch: read, filter, and write JSON in a C# console application using System.Text.Json.
How it connects
Connects JSON to streams, LINQ, serialization, HTTP requests, and C# records.

Also explained in

Compare how 35 books explain JSON →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of .NET in Action, Second Edition. The section links point to the parts of the book it draws on.