liveBook · Manning

Serialization

As explained in .NET in Action, Second Edition

Serialization is the conversion between structured in-memory objects and an external data representation such as JSON.

Serialization converts JSON to objects and objects back to JSON. When the JSON schema is known, JsonSerializer can map its data to a matching .NET type with less code than handling each JSON property directly. section 4.2.2 section 4.2.3

Filter and project jokes

Represent each JSON object as a Joke record, deserialize the array, and filter records by category with LINQ. Serialize the results, or project them to anonymous objects containing only setup and punchline. Serializer options can enable indented output and case-insensitive property matching. section 4.2.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
}

The example shows deserialization into Joke records, category filtering, and serialization of the selected results. section 4.2.3

How .NET in Action, Second Edition covers it

How deep it goes
Defines conversion and demonstrates deserialization, filtering, and projection; defers property-name correction to a later treatment.
Examples
Uses a jokes array, Joke records, category filtering, and a benchmark comparing Newtonsoft.Json with System.Text.Json.
What it assumes
Assumes a known JSON schema and demonstrates defining a corresponding .NET record.
What you can do after
Apply it via System.Text.Json to deserialize typed records, filter results with LINQ, and serialize a reduced projection.
How it connects
Connects JSON serialization with .NET records, LINQ, JSON DOM APIs, and JSON writers.

Also explained in

Compare how 24 books explain serialization →

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.