Serialization#

Serialization is the process of converting an object (its current state in memory) into a format that can be easily saved or transmitted. This can be either a binary or text format, such as JSON or XML.

The main applications of serialization are:

  1. Persistent Storage: Allows an object to be saved to disk (in a file) or to a database. After restarting the application, this data can be loaded to recreate the object in the same state it was in at the time of saving.
  2. Communication: Enables objects to be transmitted. One application serializes an object and sends it, while another receives the data and deserializes it, thereby recreating the original object.

The reverse process of serialization is deserialization – which is the reconstruction of an object from its saved (serialized) form.

The standard library provides mechanisms for serialization to both JSON and XML formats through the JsonSerializer and XmlSerializer classes, available in the System.Text.Json and System.Xml.Serialization namespaces, respectively. The external Newtonsoft.Json NuGet package is also popular for JSON serialization. It is still frequently used and offers more features and more lenient defaults, though it is less performant.

Both approaches offer an “automagic” serialization mechanism based on reflection. The serialization method takes only the object to be serialized and at runtime reads its fields and properties, then serializes it based on this information. Deserialization takes a string and an object representing the deserialized type, and uses reflection to create and initialize its instance. The serialization and deserialization process can be influenced by decorating classes and their members with attributes.

System.Text.Json#

Serialization is performed using the static JsonSerializer class.

Serialization#

var options = new JsonSerializerOptions { WriteIndented = true };
var serialized = JsonSerializer.Serialize(forecast, options);
{
  "Location": "Warsaw",
  "Temperatures": {
    "2025-12-07T22:16:44.6735555+01:00": 3.463462782637311,
    "2025-12-07T23:16:44.6735555+01:00": -19.053981902530726,
    "2025-12-08T00:16:44.6735555+01:00": -1.900355712285556,
    "2025-12-08T01:16:44.6735555+01:00": 0.549260294866361,
    "2025-12-08T02:16:44.6735555+01:00": 8.865189862795464,
    "2025-12-08T03:16:44.6735555+01:00": -18.058228230029254,
    "2025-12-08T04:16:44.6735555+01:00": 13.068063094521058,
    "2025-12-08T05:16:44.6735555+01:00": 27.008561724678614,
    "2025-12-08T06:16:44.6735555+01:00": 7.273621688485271,
    "2025-12-08T07:16:44.6735555+01:00": 27.049612806241868,
    "2025-12-08T08:16:44.6735555+01:00": 23.570338186867424,
    "2025-12-08T09:16:44.6735555+01:00": -11.79202963667603,
    "2025-12-08T10:16:44.6735555+01:00": 19.010310158995928,
    "2025-12-08T11:16:44.6735555+01:00": 24.2806090207253,
    "2025-12-08T12:16:44.6735555+01:00": 15.272542969051628,
    "2025-12-08T13:16:44.6735555+01:00": -15.570638202617841,
    "2025-12-08T14:16:44.6735555+01:00": -13.395053669977223,
    "2025-12-08T15:16:44.6735555+01:00": -18.17296011210254,
    "2025-12-08T16:16:44.6735555+01:00": 12.321830976357617,
    "2025-12-08T17:16:44.6735555+01:00": -18.447507645769615,
    "2025-12-08T18:16:44.6735555+01:00": -13.383437152501326,
    "2025-12-08T19:16:44.6735555+01:00": 28.467406712047328,
    "2025-12-08T20:16:44.6735555+01:00": -16.137085680790847,
    "2025-12-08T21:16:44.6735555+01:00": -6.799952301806021
  },
  "Summary": [
    "Hot",
    "Windy"
  ]
}

Deserialization#

Forecast? deserialized = JsonSerializer.Deserialize<Forecast>(serialized);

Attributes#

public class Person
{
    [JsonPropertyName("FirstName")]
    public string Name { get; set; }
    
    [JsonInclude] // Needed for fields (not serialized by default) and non-public members
    private DateTime DateOfBirth;
    
    [JsonIgnore]
    public int Age { get; set; }
}

Options#

The serializer is configured with a JsonSerializerOptions object. Its defaults are rather strict and differ from those of Newtonsoft.Json: property names are written exactly as declared in C#, they are matched case-sensitively during deserialization, fields are ignored (unless IncludeFields is set), and comments, trailing commas, and numbers written as strings are not accepted. JSON properties that do not match any member are silently skipped:

public record User(string Name, int Age);
string json = """{"name":"Ann","age":"25"}""";
User? p1 = JsonSerializer.Deserialize<User>(json);
// User { Name = , Age = 0 }
User? p2 = JsonSerializer.Deserialize<User>(json, JsonSerializerOptions.Web);
// User { Name = Ann, Age = 25 }
Console.WriteLine(JsonSerializer.Serialize(p2, JsonSerializerOptions.Web));
// {"name":"Ann","age":25}

Predefined read-only instances are available as static properties: JsonSerializerOptions.Default, JsonSerializerOptions.Web (.NET 9; camelCase names, case-insensitive matching, and numbers readable from strings – the defaults of ASP.NET Core), and JsonSerializerOptions.Strict (.NET 10, described below).

A JsonSerializerOptions instance caches the metadata of serialized types. Create it once and reuse it (e.g., store it in a static readonly field) instead of creating a new instance for every call.

By default, the deserializer is lenient towards incomplete or invalid input. Newer versions of .NET added options that make it stricter:

  • RespectNullableAnnotations (.NET 9) – nullable reference type annotations are enforced: deserializing null into a non-nullable property or constructor parameter (e.g., string) throws a JsonException, and so does serializing null from such a property.
  • RespectRequiredConstructorParameters (.NET 9) – a missing JSON property for a constructor parameter without a default value throws a JsonException (by default, the parameter gets the default value). Members marked with the required modifier or the [JsonRequired] attribute are always required.
  • AllowDuplicateProperties = false (.NET 10) – an object with a repeated property name throws a JsonException. By default, the last value wins, which can be abused when different parts of a system interpret the same document differently.
  • UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow (.NET 8) – JSON properties that do not match any member throw a JsonException instead of being skipped.

The JsonSerializerOptions.Strict preset (.NET 10) enables all of the above (and keeps case-sensitive matching). Each of the following calls succeeds with the default options but throws a JsonException with Strict:

var strict = JsonSerializerOptions.Strict;
JsonSerializer.Deserialize<User>("""{"Name":"Ann"}""", strict);
// JSON deserialization for type 'User' was missing required properties including: 'Age'.
JsonSerializer.Deserialize<User>("""{"Name":null,"Age":25}""", strict);
// The constructor parameter 'Name' on type 'User' doesn't allow null values. (...)
JsonSerializer.Deserialize<User>("""{"Name":"Ann","Name":"Bob","Age":25}""", strict);
// Duplicate property 'Name' encountered during deserialization of type 'User'.
JsonSerializer.Deserialize<User>("""{"Name":"Ann","Age":25,"Email":"ann@example.com"}""", strict);
// The JSON property 'Email' could not be mapped to any .NET member contained in type 'User'.

Polymorphism#

By default, an object is serialized according to its declared type (the type argument or the type of the property), not its runtime type. Serializing a derived object through a base-class reference loses the derived class’s properties – much like object slicing in C++ – and an abstract type cannot be deserialized at all, as the serializer does not know which class to instantiate. Since .NET 7, the base type can list its allowed derived types with [JsonDerivedType]. The serializer then writes a type discriminator (the $type property by default; [JsonPolymorphic] allows changing its name) and uses it during deserialization:

[JsonPolymorphic(TypeDiscriminatorPropertyName = "kind")]
[JsonDerivedType(typeof(Circle), "circle")]
[JsonDerivedType(typeof(Rectangle), "rectangle")]
public abstract record Shape;
public record Circle(double Radius) : Shape;
public record Rectangle(double Width, double Height) : Shape;
Shape[] shapes = [new Circle(1.5), new Rectangle(2, 3)];
string json = JsonSerializer.Serialize(shapes);
// [{"kind":"circle","Radius":1.5},{"kind":"rectangle","Width":2,"Height":3}]
Shape[]? deserialized = JsonSerializer.Deserialize<Shape[]>(json);
// deserialized[0] is Circle { Radius = 1.5 }

Only the listed types are allowed: serializing an unlisted derived type throws a NotSupportedException, and an unknown discriminator value throws a JsonException. The discriminator must be the first property of the JSON object, unless AllowOutOfOrderMetadataProperties (.NET 9) is enabled. The allow-list is a deliberate security measure – Newtonsoft.Json offers TypeNameHandling, which writes full .NET type names into JSON; used with untrusted input, it lets an attacker make the deserializer instantiate unexpected types, a well-known source of vulnerabilities.

Source Generation#

Reflection-based serialization inspects types at run time, which costs startup time and memory, and is incompatible with trimming and Native AOT compilation – in such applications (including .NET 10 file-based apps, dotnet run app.cs, which enable PublishAot by default), it is disabled altogether. The alternative is the source generator: a partial class deriving from JsonSerializerContext lists the serialized types with [JsonSerializable], and the compiler generates their serialization metadata and code at build time:

[JsonSerializable(typeof(Forecast))]
[JsonSourceGenerationOptions(WriteIndented = true)]
internal partial class ForecastContext : JsonSerializerContext;
string json = JsonSerializer.Serialize(forecast, ForecastContext.Default.Forecast);
Forecast? deserialized = JsonSerializer.Deserialize(json, ForecastContext.Default.Forecast);

ForecastContext.Default.Forecast is a generated JsonTypeInfo<Forecast> object. Alternatively, the context can be assigned to JsonSerializerOptions.TypeInfoResolver, so that calls taking options also work without reflection.

Newtonsoft.Json#

Serialization is performed using the static JsonConvert class.

Serialization#

var serialized = JsonConvert.SerializeObject(forecast, Formatting.Indented);
{
  "Location": "Warsaw",
  "Temperatures": {
    "2025-12-07T22:15:35.4733681+01:00": -17.084698423041804,
    "2025-12-07T23:15:35.4733681+01:00": -15.132029763809939,
    "2025-12-08T00:15:35.4733681+01:00": 5.772196161399023,
    "2025-12-08T01:15:35.4733681+01:00": 8.832614803522482,
    "2025-12-08T02:15:35.4733681+01:00": -19.629052158164615,
    "2025-12-08T03:15:35.4733681+01:00": 7.6065850260430565,
    "2025-12-08T04:15:35.4733681+01:00": -19.710601981383896,
    "2025-12-08T05:15:35.4733681+01:00": 13.65822297707701,
    "2025-12-08T06:15:35.4733681+01:00": 7.43438191592119,
    "2025-12-08T07:15:35.4733681+01:00": -18.847585808274825,
    "2025-12-08T08:15:35.4733681+01:00": 19.497623200834,
    "2025-12-08T09:15:35.4733681+01:00": 1.3729643304821089,
    "2025-12-08T10:15:35.4733681+01:00": -4.353138125059385,
    "2025-12-08T11:15:35.4733681+01:00": 14.690275394792117,
    "2025-12-08T12:15:35.4733681+01:00": 14.823212353915117,
    "2025-12-08T13:15:35.4733681+01:00": 1.272628008894607,
    "2025-12-08T14:15:35.4733681+01:00": 29.740090341863343,
    "2025-12-08T15:15:35.4733681+01:00": 13.979668721485552,
    "2025-12-08T16:15:35.4733681+01:00": 23.9485046073197,
    "2025-12-08T17:15:35.4733681+01:00": -14.917400243602472,
    "2025-12-08T18:15:35.4733681+01:00": 22.090026162918193,
    "2025-12-08T19:15:35.4733681+01:00": 3.2913333012331627,
    "2025-12-08T20:15:35.4733681+01:00": 14.130944452865734,
    "2025-12-08T21:15:35.4733681+01:00": -10.767305294541261
  },
  "Summary": [
    "Rain",
    "Cold",
    "Humid"
  ]
}

Deserialization#

Forecast? deserialized = JsonConvert.DeserializeObject<Forecast>(serialized);

Attributes#

public class Person
{
    [JsonProperty("FirstName")]
    public string Name { get; set; }

    [JsonProperty] // Needed for non-public members (unlike System.Text.Json, public fields are serialized by default)
    private DateTime DateOfBirth;

    [JsonIgnore]
    public int Age { get; set; }
}

Example#