Introduction
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 the JsonNode class, forcing developers to lose the benefits of compiler support in a strongly typed language.
Example JSON
Consider the JSON below:
string json = """
{
"Name": "Alice",
"Age": 30,
"NonExistentStringField": "foo",
"NonExistingIntField": 48
}
""";
Let's say, for our needs, we require only the Name and Age fields. Not a big deal! We can declare only the meaningful properties.
public class Person
{
public string Name { get; set; } = "";
public int Age { get; set; }
}
Deserialization
Deserialization will work as intended:
Person? person = JsonSerializer.Deserialize<Person>(json);
Console.WriteLine(person?.Name);
Console.WriteLine(person?.Age);
Output
Alice
30
Real-World Scenario
In reality, JSON responses returned by external APIs might contain quite large structures, while only a fraction of those might be needed.
This, however, should not turn developers away from using strongly typed deserialization, as we saw in the example above.
Summary
When deserializing JSON in .NET, you do not need to define every property present in the JSON payload. The serializer can successfully map only the properties that exist in your DTO and ignore the rest. This allows developers to keep DTOs focused on the data they actually need while still benefiting from strong typing, compile-time checks, and improved maintainability.
0 Comments
Log in to join the conversation.No comments yet. Be the first to share your thoughts.