JamesNK / Newtonsoft.Json

Json.NET is a popular high-performance JSON framework for .NET
https://www.newtonsoft.com/json
MIT License
10.71k stars 3.24k forks source link

Add support for the four `System.Text.Json` types #2910

Open RenderMichael opened 10 months ago

RenderMichael commented 10 months ago

I use System.Text.Json but a number of my dependencies use JSON.NET. Some of these dependencies serialize arbitrary objects, others take types like Dictionary<string, object?>.

This makes deserializing with STJ more difficult, since the arbitrary objects and the object?s in the above dictionary are either JsonNode or JsonElement, and when my dependencies serialize, the serialization does not work.

Could JSON.NET add converters for the four STJ types (JsonValue, JsonArray, JsonObject, and JsonElement)? Adding support for this would make the path to STJ 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.

RenderMichael commented 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);