You don't need to create all properties inside a DTO to successfully deserialize
The example below might seem like very simple advice, but I found people across many codebases do not know this. This, in turn, leads to excessive usage of JsonNode class, forcing developers to lose benefits of compiler support in a strongly typed language.
Consider the JSON below
string json = """
{
"Name": "Alice",
"Age": 30,
"NonExistentStringField": "foo",
"NonExistingIntField": 48
}
""";
Let’s say, for our needs, we require only Name and Age fields. Not a big deal! We can declare only meaningful properties.
public class Person
{
public string Name { get; set; } = "";
public int Age { get; set; }
}
Deserialization will work as intended
Person? person = JsonSerializer.Deserialize<Person>(json);
Console.WriteLine(person?.Name);
Console.WriteLine(person?.Age);
Returning
Alice
30
In reality, JSON responses returned by external APIs might contain quite a big structures, while only a fraction of those might be needed. This, however, should not turn away developers from resorting to strongly typed deserialization, as we saw in the example above.