C# Tips

Today's C# Tip

System.Text.Json - Why does Deserialize() return empty values?

.NET Core 3.0 introduced System.Text.Json namespace which includes some of JSON classes. Among the classes, JsonSerializer is probably mostly used for JSON Serialization and Deserialization.

When using System.Text.Json.JsonSerializer class for JSON Deserialization, sometimes you might make a mistake of using public fields instead of public properties in deserialization class. If deserialization class has public fields, JsonSerializer.Deserialize() method will return empty values such as 0, without any warning or error. So be careful!

Here is an example. Please note that the code below used public filed in Person class.

public class Person
{
    public int Id;  // WRONG!
    public decimal Temp;
}

string jsonString = "{\"Id\":1,\"Temp\":78.12}";
var personObj = JsonSerializer.Deserialize<Person>(jsonString);

To fix the issue, we need to use public properties as below.

public class Person
{
    public int Id {get; set;}
    public decimal Temp {get; set;}
}