-
Notifications
You must be signed in to change notification settings - Fork 4.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
System.Text.Json.JsonSerializer.Serialize, when JsonIgnoreAttribute and "required" used together, throw exception #78443
Comments
Tagging subscribers to this area: @dotnet/area-system-text-json, @gregsdennis Issue DetailsDescriptionWhen JsonIgnoreAttribute and C# required used together, throw exception public void TestRequired()
{
var model = new TestModel
{
Str1 = "a",
Str2 = "b"
};
var json = System.Text.Json.JsonSerializer.Serialize(model);
Console.WriteLine(json);
}
public class TestModel
{
[System.Text.Json.Serialization.JsonIgnore]
public required string Str1 { get; set; }
[JsonPropertyName("s_str2")]
public required string Str2 { get; set; }
} Configuration.NET 7 Regression?Other information
|
This scenario was blocked by design because we won't ever be able to source generate such code (we must provide property when it's required)... You can workaround it by creating contract resolver modifier and removing this property - it will only work with reflection-based serializer though. Here is a workaround: using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
JsonSerializerOptions options = new()
{
TypeInfoResolver = new DefaultJsonTypeInfoResolver()
{
Modifiers =
{
RemoveIgnoredPropertiesFromContract
}
}
};
var model = new TestModel
{
Str1 = "a",
Str2 = "b"
};
var json = JsonSerializer.Serialize(model, options);
Console.WriteLine(json);
// {"s_str2":"b"}
static void RemoveIgnoredPropertiesFromContract(JsonTypeInfo typeInfo)
{
if (typeInfo.Kind != JsonTypeInfoKind.Object)
return;
List<JsonPropertyInfo> properties = new();
foreach (var prop in typeInfo.Properties)
{
if (prop.AttributeProvider != null && prop.AttributeProvider.IsDefined(typeof(JsonIgnoreAttribute), inherit: true))
{
continue;
}
properties.Add(prop);
}
typeInfo.Properties.Clear();
foreach (var property in properties)
{
typeInfo.Properties.Add(property);
}
}
public class TestModel
{
[JsonIgnore]
public required string Str1 { get; set; }
[JsonPropertyName("s_str2")]
public required string Str2 { get; set; }
} I'm closing this as by design though. |
Description
When JsonIgnoreAttribute and C# required used together, throw exception
Configuration
.NET 7
Windows
Regression?
Other information
The text was updated successfully, but these errors were encountered: