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

Time:11-22

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: {}

CodePudding user response:

try

var result 2 = JsonSerializer.Serialize(testClass);

CodePudding user response:

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}
  •  Tags:  
  • c#
  • Related