I'm working with a POCO class in .NET 5.0 that I need to serialize and deserialize to and from the browser, and this is in a library where I don't want to have to tell the users which serializers they must use.
So I'm trying to make it work with both Newtonsoft.Json and System.Text.Json.
My problem is that values stored in fields with type object aren't being deserialized into their original type, in System.Text.Json.
using Shouldly;
using Xunit;
using SJ = System.Text.Json;
using NJ = Newtonsoft.Json;
public class SerializationTests
{
[Fact]
public void TestNJ()
{
var nvp = new NVP { Name = "a name", Value = "a value" };
var s = NJ.JsonConvert.SerializeObject(nvp);
var d = NJ.JsonConvert.DeserializeObject<NVP>(s);
d.ShouldBeEquivalentTo(nvp);
}
[Fact]
public void TestSJ()
{
var nvp = new NVP { Name = "a name", Value = "a value" };
var s = SJ.JsonSerializer.Serialize(nvp);
var d = SJ.JsonSerializer.Deserialize<NVP>(s);
d.ShouldBeEquivalentTo(nvp);
}
}
TestNJ passes.
TestSJ throws an exception:
Expected value to be System.String but was System.Text.Json.JsonElement'
In the debugger it's clear what's going on.
In both TestNJ() and TestSJ(), at the beginning, nvp
has the value:
nvp: {NVP}
Name [string]: "a name"
Value [object]: " a value"
In both, after serialization, s
has the value I'd expect:
"{\"Name\":\"a name\",\"Value\":\"a value\"}"
But where in TestNJ(), after deserialization, d
has the value:
d: {NVP}
Name [string]: "a name"
Value [object]: " a value"
In TestSJ(), d
has the value:
d: {NVP}
Name [string]: "a name"
Value [object]: ValueKind = String: "a value"
What is going on here? How do I get System.Text.Json to actually deserialize this type?