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)

Most upvoted comments

image

maybe we should update the document, to make it clear.

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:

Unhandled exception. System.InvalidOperationException: JsonPropertyInfo 'Items' defined in type 'TestDto' is marked required but does not specify a setter.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_JsonPropertyRequiredAndNotDeserializable(JsonPropertyInfo jsonPropertyInfo)
   at System.Text.Json.Serialization.Metadata.JsonPropertyInfo.Configure()
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo.InitializePropertyCache()
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo.Configure()
   at System.Text.Json.Serialization.Metadata.JsonTypeInfo.<EnsureConfigured>g__ConfigureLocked|143_0()
   at System.Text.Json.JsonSerializerOptions.GetTypeInfoInternal(Type type, Boolean ensureConfigured, Boolean resolveIfMutable)
   at System.Text.Json.JsonSerializer.GetTypeInfo(JsonSerializerOptions options, Type inputType)
   at System.Text.Json.JsonSerializer.GetTypeInfo[T](JsonSerializerOptions options)
   at System.Text.Json.JsonSerializer.Serialize[TValue](TValue value, JsonSerializerOptions options)

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.