I have a structure of objects that I serialize to JSON, and there is one path that can have circular references. This problem can be solved using PreserveReferencesHandling.Objects
, but unfortunately it creates another problem because it adds $id
properties to all the objects. I don't want to clutter the serialized data, as it's supposed to be human readable and editable.
So, the question is there any way to make it add $id
only to those objects that actually are included into reference loops?
Asked
Active
Viewed 162 times
0

Pavel Anikhouski
- 21,776
- 12
- 51
- 66

user626528
- 13,999
- 30
- 78
- 146
-
In order to only serialize `$id` properties for objects that participate in reference loops, it would be necessary to make an initial pass through the serialization graph to identify all such objects -- but Json.NET is a single-pass serializer, so that isn't easily done. – dbc May 12 '21 at 19:48
-
1You could restrict `#id` properties to specific types if that helps, see e.g. [Newtonsoft.Json.JsonSerializationException “Self referencing loop detected” in library code](https://stackoverflow.com/a/32275608/3744182) or [Disable JSON.Net PreserveReferencesHandling for single external type](https://stackoverflow.com/q/44515823/3744182). – dbc May 12 '21 at 19:48
-
@dbc I can do loop detection before serialization, but in this case it would be necessary to somehow use this info in Json.NET to only append ids where necessary. – user626528 May 12 '21 at 19:56