-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Description
Description
Following the sample code i "What's new in .NET 8" the deserialization does not work as expected, and the output is different.
The following only allows for Company to be set:
[JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)]
class CustomerInfo
{
public string Name { get; } = "Anonymous";
public CompanyInfo Company { get; } = new() { Name = "N/A", PhoneNumber = "N/A" };
}
If I add [JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)] to the Name property it will result in the following exception:
Unhandled exception. System.InvalidOperationException: Property 'Name' on type 'CustomerInfo' is marked with JsonObjectCreationHandling.Populate but it doesn't support populating. This can be either because the property type is immutable or it could use a custom converter.
On the other hand, if I wrap the name in a class, and use that as a container it works. As long as the built-in types (string etc) are not read-only.
Reproduction Steps
Create a new console application with the code from the docs:
using System.Text.Json;
CustomerInfo customer =
JsonSerializer.Deserialize<CustomerInfo>("""{"Name":"John Doe","Company":{"Name":"Contoso"}}""")!;
Console.WriteLine(JsonSerializer.Serialize(customer));
class CompanyInfo
{
public required string Name { get; set; }
public string? PhoneNumber { get; set; }
}
[JsonObjectCreationHandling(JsonObjectCreationHandling.Populate)]
class CustomerInfo
{
// Both of these properties are read-only.
public string Name { get; } = "Anonymous";
public CompanyInfo Company { get; } = new() { Name = "N/A", PhoneNumber = "N/A" };
}
Expected behavior
Output:
{"Name":"John Doe","Company":{"Name":"Contoso","PhoneNumber":null}}
Actual behavior
Output:
{"Name":"Anonymous","Company":{"Name":"Contoso","PhoneNumber":"N/A"}}
Name is not set as it's read-only and a built-in type.
Regression?
No response
Known Workarounds
Wrap the built-in type in a new class, and do not mark it as read-only in that container.
Configuration
Tried on both Windows and macOS using 8.0.100-rc.1.23463.5
Other information
No response