Wednesday, October 23, 2024

.NET 9.0: Out-of-order Metadata Reading in System.Text.Json

Release of .NET 9.0 is like 3 weeks away and in this post, let's have a look at one of the most awaited System.Text.Json features.

Let's have a look at an example.

Consider the below types.
[JsonDerivedType(typeof(Student)"student")]
record Person(string Name);

record Student(string Namestring StudentId) : Person(Name);
The following code will throw an error on Deserialize.
using System.Text.Json.Serialization;
using System.Text.Json;

JsonSerializerOptions options = new();

Person person = new Employee("John Doe""STU001");
string serializedPerson = JsonSerializer.Serialize(personoptions);
// {"$type":"student","StudentId":"STU001","Name":"John Doe"}

// Change the order of $type
serializedPerson = """
{
    
"StudentId":"STU001",
    
"Name":"John Doe",
    
"$type":"student"
}
"""
;

person = JsonSerializer.Deserialize<Person>(serializedPersonoptions)!; // Exception
// System.Text.Json.JsonException: The metadata property is either not supported by the type or is not the first property in the deserialized JSON object.
The reason is (as the exception says) that the metadata property $type is not the first property in the JSON string, and it has to be. While there is a reason for that requirement, until .NET 9, it was a known limitation (see #dotnet/runtime/issues/72604).

Finally, in .NET 9, we can enable AllowOutOfOrderMetadataProperties in JsonSerializerOptions.
JsonSerializerOptions options = new()
{
    AllowOutOfOrderMetadataProperties = true
};
And now the above would work just fine.

Hope this helps.

Happy Coding.

Regards,
Jaliya

No comments:

Post a Comment