Skip to content

JsonSerializer support for immutable classes and structs. #29895

@johanneshoehn

Description

@johanneshoehn

A common pattern is to make data objects immutable for many different reasons.
For example Point:

public class Point
{
    int X { get; }

    int Y { get; }

    public Point(int x, int y) => (X, Y) = (x, y);

    public void Deconstruct(out int x, out int y) => (x, y) = (X, Y);
}

It would be very helpful if JsonSerializer supported immutable classes/structs like that, especially since Newtonsoft Json.NET supports deserialization through the constructor.

However there are a few issues surrounding immutable types:

  • Constructor parameter names are usually camelCase while Properties are PascalCase. One way to solve this is by setting JsonSerializerOptions.PropertyNameCaseInsensitive in to true. Another way is to use the Deconstruct-pattern introduced in C# 7.0, instead of Properties for serialization.

  • There may be several constructors (and Deconstruct methods). So it's not always clear which to use. Newtonsoft Json.NET uses a JsonConstructorAttribute.htm, which has the disadvantage that the data objects need to know about serialization.

  • Constructor parameters, properties and Deconstruct method parameters might not match up, possibly leading to confusing situations where deserializing a previously serialized object does not work.

  • Immutable structs always still have a default parameterless constructor.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions