How to fix 'System.Text.Json Deserialize() return empty values'

By FoxLearn 11/1/2024 1:23:37 PM   88
To fix issues where System.Text.Json.Deserialize() returns empty or default values, follow these steps.

Here's an example demonstrating the issue: the code below uses public fields in the Person class, which can lead to empty or default values during deserialization.

public class Person
{
    //WRONG
    public int Id;
    public string Name;
}
 
string jsonString = "{\"Id\":1,\"Name\"Lucy}";
var obj = JsonSerializer.Deserialize<Person>(jsonString);

To fix the issue, we should use public properties instead of fields, as shown below.

For example:

public class People
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Ensure that your data class uses public properties with getters and setters, not public fields.

Make sure the JSON property names match the property names in your class. JSON property names are case-sensitive by default. For example, if your JSON looks like this:

{ "id": 1, "name": "Example" }

Your class properties should be named Id and Name. If you want case insensitivity, you can set the option as shown below.

var options = new JsonSerializerOptions
{
    PropertyNameCaseInsensitive = true
};
var obj = JsonSerializer.Deserialize<People>(jsonString, options);

By following these steps, you should be able to resolve issues with empty or default values during deserialization with System.Text.Json.

Related