Open RenderMichael opened 10 months ago
Note on the existing functionality:
System.Text.Json.Nodes.JsonValue? stjTrue = System.Text.Json.Nodes.JsonValue.Create<bool>(true);
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(stjTrue); // Newtonsoft.Json.JsonSerializationException : Self referencing loop detected for property 'Root' with type 'System.Text.Json.Nodes.JsonValueNotTrimmable`1[System.Boolean]'. Path ''.
Console.WriteLine(serialized);
System.Text.Json.Nodes.JsonArray? arr = System.Text.Json.JsonSerializer.Deserialize<System.Text.Json.Nodes.JsonArray>("[1,2,3]");
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(arr); // Newtonsoft.Json.JsonSerializationException : Self referencing loop detected for property 'Parent' with type 'System.Text.Json.Nodes.JsonArray'. Path '[0]'.
Console.WriteLine(serialized);
For JsonElement
, no exception is thrown but serialization doesn't work right
System.Text.Json.JsonElement arr = System.Text.Json.JsonSerializer.Deserialize<System.Text.Json.JsonElement>("[1,2,3]");
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(arr);
Console.WriteLine(serialized); // {"ValueKind":2}
An empty object actually works
var arr = System.Text.Json.JsonSerializer.Deserialize<System.Text.Json.Nodes.JsonObject>("{}");
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(arr);
Console.WriteLine(serialized); // {}
But as soon as we add a property...
var arr = System.Text.Json.JsonSerializer.Deserialize<System.Text.Json.Nodes.JsonObject>(@"{""myProp"": ""myVal""}");
string serialized = Newtonsoft.Json.JsonConvert.SerializeObject(arr); // Newtonsoft.Json.JsonSerializationException : Self referencing loop detected for property 'Parent' with type 'System.Text.Json.Nodes.JsonObject'. Path 'myProp'.
Console.WriteLine(serialized);
I use
System.Text.Json
but a number of my dependencies use JSON.NET. Some of these dependencies serialize arbitrary objects, others take types likeDictionary<string, object?>
.This makes deserializing with
STJ
more difficult, since the arbitrary objects and theobject?
s in the above dictionary are eitherJsonNode
orJsonElement
, and when my dependencies serialize, the serialization does not work.Could JSON.NET add converters for the four STJ types (
JsonValue
,JsonArray
,JsonObject
, andJsonElement
)? Adding support for this would make the path toSTJ
smoother, as well as making it easier to maintain both dependencies.I know JSON.NET is mostly in maintenance mode, but this improvement is justified in my opinion. If there's interest in this, I could try to implement it myself.