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























