I am trying to use System.Text.Json library for performance improvement. When I am trying to convert it, System.Text.Json is not able to deserialize the object but Newtonsoft.Json able to do so.
How to fix it for System.Text.Json?
fiddle https://dotnetfiddle.net/Ukzw6h
using System;
using System.Text.Json;
using Newtonsoft.Json;
public class Person {
public string Name;
public string Role;
}
public class Program
{
public static void Main()
{
string json = """{"Name":"John","Role":"Software Engineer"}""";
using JsonDocument doc = JsonDocument.Parse(json);
JsonElement jsonElement = doc.RootElement;
var personText = System.Text.Json.JsonSerializer.Deserialize<Person>(jsonElement.GetRawText());
Console.WriteLine($"from System.Text.Json {personText.Role}");
var personNewton = JsonConvert.DeserializeObject<Person>(jsonElement.GetRawText());
Console.WriteLine($"from Newtonsoft.Json {personNewton.Role}");
}
}
output:
from System.Text.Json
from Newtonsoft.Json Software Engineer
NameandRoleproperties in thePersonclass.[JsonInclude]attribute.