I found out how to use System.Text.Json with immutable objects using the [JsonConstructor] attribute (see: How to use immutable types), and separately how to preserve references with .Net 5.
Unfortunately, when trying to combine the 2, the following error apears:
NotSupportedException
Reference metadata is not honored when deserializing types using parameterized constructors.
According to the first link, this is to be expected:
This feature can't be used to preserve value types or immutable types. On deserialization, the instance of an immutable type is created after the entire payload is read. So it would be impossible to deserialize the same instance if a reference to it appears within the JSON payload.
Deserializing does seem to work with Newtonsoft.Json though (even when serializing with System.Text.Json).
Is there any other way to make deserializing work with System.Text.Json as well?