简体   繁体   中英

Serialization -> how to change Newtonsoft.Json to System.Text.Json?

I discovered a different behaviour when I want to serialize an object of type INTERFACE in System.Text.Json.

public class ITestClass
{
}

public class TestClass : ITestClass
{
    public int MyProperty { get; set; }
}

Newtonsoft.Json:

var result1 = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(testClass));
var result2 = Encoding.UTF8.GetString(result1); // {"MyProperty":5}

System.Text.Json:

var result1 = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(testClass);
var result2 = Encoding.UTF8.GetString(result1); // {}

How can I get the same result in System.Text.Json like in Newtonsoft.Json? I want to get: {"MyProperty":5} not: {}

try

var result 2 = JsonSerializer.Serialize(testClass);

OK, I know. I need to cast an object of type interface to "object":

var result1 = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes((object)testClass);
var result2 = Encoding.UTF8.GetString(result1); // {"MyProperty":5}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM