-
Notifications
You must be signed in to change notification settings - Fork 5.2k
Description
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
camelCasewhile Properties arePascalCase. One way to solve this is by settingJsonSerializerOptions.PropertyNameCaseInsensitivein totrue. Another way is to use theDeconstruct-pattern introduced in C# 7.0, instead of Properties for serialization. -
There may be several constructors (and
Deconstructmethods). 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
Deconstructmethod 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.