System.Text.Json: writing

System.Text.Json is part of the shared framework, so a console app writes JSON without a package and without the network. The serializer walks the public properties of an object and writes them as members of a JSON object; the lesson shows the settings that a real service uses, and the next one reads the text back.

Serialize a record

The payload is a record with a nested array of records. One call with WriteIndented gives the readable form, a second call with no options gives the compact one:

using System.Text.Json; var order = new Order( 42, "Ada", new[] { new Line("pen", 2, 1.50m), new Line("paper", 10, 0.25m) }); var indented = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; Console.WriteLine(JsonSerializer.Serialize(order, indented)); Console.WriteLine(JsonSerializer.Serialize(order)); Console.WriteLine($"length {JsonSerializer.Serialize(order).Length}"); record Order(int Id, string Customer, Line[] Lines); record Line(string Sku, int Quantity, decimal Price);

dotnet run

{
  "id": 42,
  "customer": "Ada",
  "lines": [
    {
      "sku": "pen",
      "quantity": 2,
      "price": 1.50
    },
    {
      "sku": "paper",
      "quantity": 10,
      "price": 0.25
    }
  ]
}
{"Id":42,"Customer":"Ada","Lines":[{"Sku":"pen","Quantity":2,"Price":1.50},{"Sku":"paper","Quantity":10,"Price":0.25}]}
length 119

Without the naming policy the members keep the names of the properties, so the compact form starts with Id and not id. The decimal 1.50m keeps its two decimal places in the JSON, because the serializer writes the scale of the decimal and a price should not become 1.5 on the wire. The compact form of this small order is 119 characters.

Naming, nulls and enums

A service usually leaves null members out and writes an enum as its name rather than its number. JsonPropertyName renames one member when the policy is not enough:

using System.Text.Json; using System.Text.Json.Serialization; var order = new Order(7, null, new[] { new Line("pen", 2, 1.50m) }); var options = new JsonSerializerOptions { WriteIndented = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, }; Console.WriteLine(JsonSerializer.Serialize(order, options)); var tagged = new Tagged("pen", 9.99m, Priority.High); Console.WriteLine(JsonSerializer.Serialize(tagged, new JsonSerializerOptions { Converters = { new JsonStringEnumConverter() }, })); var map = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2 }; Console.WriteLine(JsonSerializer.Serialize(map)); record Order(int Id, string? Customer, Line[] Lines); record Line(string Sku, int Quantity, decimal Price); record Tagged( [property: JsonPropertyName("name")] string Name, decimal Price, Priority Priority); enum Priority { Low, Normal, High, }

dotnet run

{
  "id": 7,
  "lines": [
    {
      "sku": "pen",
      "quantity": 2,
      "price": 1.50
    }
  ]
}
{"name":"pen","Price":9.99,"Priority":"High"}
{"a":1,"b":2}

The null customer is missing from the first object instead of being written as null. The second object shows two rules at once: the naming policy is absent, so Price and Priority keep their names, and the attribute still renames the first member to name. A dictionary becomes an object with its keys as members.

What becomes a property

The options object is expensive to create and cheap to reuse, so a service keeps one static instance; the lesson on performance measures the difference between a cached and a fresh instance. The serializer can also write the same shape from metadata generated at build time, which the next part mentions.

Generated code for a hot path

A source generator in the SDK can write the serialization code at build time instead of reflecting at run time. It needs a JsonSerializerContext, which is a partial class the generator fills in; the SDK carries the generator, so this compiles without a package. The lesson on source generators explains the mechanism and why a generator from NuGet does need the network.

Exercises

  1. Add a Total property to Order that sums the lines and find it in the JSON.
  2. Serialize the same order with JsonIgnoreCondition.Never and compare the first two objects.
  3. Serialize a DateTime and read the format of the string it becomes.
  4. Serialize a list of orders and count the objects in the text.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which namespace holds JsonSerializer?

    Answer

    System.Text.Json

    System.Text.Json is the serializer of the shared framework.

  2. What does WriteIndented = true change?

    Answer

    The text gets line breaks and indentation

    It is a formatting option only; the members and their order are the same.

  3. What does this program print? using System.Text.Json; Console.WriteLine(JsonSerializer.Serialize(new { a = 1 }));

    Answer

    {"a":1}

    The default is compact, and the property keeps the name it was declared with.

  4. What does this program print? using System.Text.Json; Console.WriteLine(JsonSerializer.Serialize(1.5m));

    Answer

    1.5

    A decimal with scale 1 writes one decimal place.

  5. Which option writes the members in camelCase?

    Answer

    PropertyNamingPolicy = JsonNamingPolicy.CamelCase

    The naming policy is what changed Id to id in the measured output.

  6. What does DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull do?

    Answer

    Leaves a null member out of the object

    The absent customer member of the second program is that setting.

  7. What does this program print? using System.Text.Json; Console.WriteLine(JsonSerializer.Serialize(new[] { 1, 2 }));

    Answer

    [1,2]

    An array becomes a JSON array in order.

  8. Which members does the serializer write by default?

    Answer

    Public properties

    A field needs IncludeFields; a property is the default unit.

  9. Which attribute renames one property in the JSON?

    Answer

    JsonPropertyName

    The measured Tagged record wrote name instead of Name because of it.

  10. What does this program print? using System.Text.Json; Console.WriteLine(JsonSerializer.Serialize("hi"));

    Answer

    "hi"

    A string is a JSON string and keeps its quotes in the output text.

The code on this page was built with the .NET SDK 10.0.303 and run on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev