runtime: dotnet 7 System.Text.Json JsonSerializer.Serialize exception: is marked required but does not specify a setter.
Description
using JsonSerializer.Serialize to Serialize object.
Reproduction Steps
using System.Text.Json;
using System.Text.Json.Serialization;
TestDto t = new() { Items = new() };
string jsonString = JsonSerializer.Serialize(t);
Console.WriteLine(jsonString);
public class TestDto
{
public string? Field1 { get; set; }
[JsonIgnore]
public required List<string> Items { get; set; }
}
Expected behavior
no exception
Actual behavior
exception throws
Regression?
No response
Known Workarounds
No response
Configuration
No response
Other information
No response
About this issue
- Original URL
- State: closed
- Created a year ago
- Comments: 15 (9 by maintainers)
That’s not accurate. As mentioned the exception stems from contract validation and is not part of the serialization contract for required properies. This should be evident from the stacktrace of the reproduction:
We might want to update the documentation for
JsonPriopertyInfo.IsRequired
to mention that it is not compatible with properties that don’t have a setter or are ignoring their setter.