Serialize JSON with explicit names and validation options
Use JsonSerializer.Serialize to produce JSON from an object and JsonSerializer.Deserialize<T> to read it back. Define the naming and validation options as part of the boundary contract. A JSON document can be syntactically valid while still omitting required information or containing unexpected fields.
The example targets .NET 10 and distinguishes three input errors. A required property must be present. A non-nullable property must not contain null when annotation enforcement is enabled. Unknown properties are rejected when the unmapped-member policy is strict.
Run a round trip and invalid inputs
Create a console project with dotnet new console -n JsonDemo -f net10.0. Keep nullable analysis enabled. Replace Program.cs and run dotnet run --project JsonDemo from its parent directory.
using System;
using System.Globalization;
using System.Text.Json;
using System.Text.Json.Serialization;
var options = new JsonSerializerOptions {
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = false,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
RespectNullableAnnotations = true
};
var invoice = new Invoice { Number = "INV-7", Total = 12.5m };
var json = JsonSerializer.Serialize(invoice, options);
Console.WriteLine(json);
var restored = JsonSerializer.Deserialize<Invoice>(json, options)
?? throw new JsonException("Expected an invoice object.");
Console.WriteLine($"{restored.Number} {restored.Total.ToString(CultureInfo.InvariantCulture)}");
CheckRejected("Missing", """{"total":12.5}""");
CheckRejected("Null", """{"number":null,"total":12.5}""");
CheckRejected("Unknown", """{"number":"INV-7","total":12.5,"extra":true}""");
CheckRejected("Wrong case", """{"Number":"INV-7","total":12.5}""");
void CheckRejected(string label, string input) {
try {
JsonSerializer.Deserialize<Invoice>(input, options);
throw new InvalidOperationException($"Expected {label} input to be rejected.");
} catch (JsonException) {
Console.WriteLine($"{label} rejected");
}
}
sealed class Invoice {
public required string Number { get; init; }
public required decimal Total { get; init; }
}
Expected output:
{"number":"INV-7","total":12.5}
INV-7 12.5
Missing rejected
Null rejected
Unknown rejected
Wrong case rejected
The exact property order shown comes from this model's declaration order in this example. Consumers should identify JSON properties by name rather than treat object member order as a business contract. The decimal value is written as a JSON number, independent of the machine's display culture.
Separate the constraints
required makes presence mandatory for this serializer contract. It does not mean that an empty string, negative total or duplicate invoice number is valid. Perform those domain checks after parsing and before accepting the object into application state.
RespectNullableAnnotations adds supported runtime checks for non-nullable members. It is available from .NET 9, so copying this complete configuration into older targets requires adjustment. Its scope is limited. It does not enforce top-level nullability or nullable annotations on collection element types. The explicit ?? throw therefore rejects a JSON root value of null.
UnmappedMemberHandling.Disallow rejects fields that do not belong to the model. That is useful for tightly controlled commands, where an unexpected field can indicate a typo. For independently evolving public APIs, ignoring unknown fields may be an intentional compatibility policy. Choose the behavior rather than applying strictness indiscriminately.
Reuse a deliberate configuration
The sample uses camelCase with case-sensitive input. ASP.NET Core and HTTP JSON helpers have their own web defaults, which differ from a fresh options instance. Share the intended configuration at the boundary so a standalone utility and a web endpoint do not silently interpret the same document differently.
Reuse an options instance after configuration. Once it has been used, treat it as immutable. If a different endpoint requires another policy, create a separate configured instance rather than changing a shared one during requests.
Avoid assembling JSON by concatenating strings. The serializer handles escaping for quotes, control characters and Unicode content. Add explicit converters only when the contract requires a representation the built-in behavior does not provide.
This example uses reflection-based serialization in a normal console build. Native AOT or trimmed applications should evaluate source generation and the resulting type metadata requirements separately. Successful execution here does not establish that every model is preserved under those deployment modes.
References




Question provenance
This article addresses How do I turn a C# object into a JSON string in .NET? , asked by Hui on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored for current .NET. No answer text or code is reproduced.
Author: Herman Schoenfeld