英文:
How to ignore a property in runtime deserialization ASP.NET Core app
问题
以下是代码的翻译部分:
我在我的ASP.NET Core 6.0应用程序中有一个用于JSON反序列化的类:
public class DocumentInfo
{
[JsonProperty("FileName", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName("FileName")]
public string FileName { get; set; }
[JsonPropertyName("Template")]
[JsonProperty("FileName", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
public string Template { get; set; }
[JsonProperty("VersionBody", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName("VersionBody")]
public VersionBody VersionBody { get; set; }
[Newtonsoft.Json.JsonIgnore]
public string FileExtension => Path.GetExtension(this.FileName);
}
Controller API方法:
[HttpPost(template: "generate"), Consumes("application/json"), Produces("application/json")]
public FileStreamResult? Generate([FromBody] DocumentInfo request,
CancellationToken cancellationToken = default)
有时序列化查询中可能没有模板属性。然后控制器应该忽略它。但现在在反序列化期间我收到一个错误,说该字段是必需的,但缺失。
我尝试了:
[DataMember(IsRequired = false)]
但这对我没有帮助。
如何在运行时避免反序列化错误?
英文:
I have class for JSON deserialization in my ASP.NET Core 6.0 application:
public class DocumentInfo
{
[JsonProperty("FileName", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName("FileName")]
public string FileName { get; set; }
[JsonPropertyName("Template")]
[JsonProperty("FileName", Required = Required.DisallowNull, NullValueHandling = NullValueHandling.Ignore)]
public string Template { get; set; }
[JsonProperty("VersionBody", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName("VersionBody")]
public VersionBody VersionBody { get; set; }
[Newtonsoft.Json.JsonIgnore]
public string FileExtension => Path.GetExtension(this.FileName);
}
Controller API method:
[HttpPost(template:"generate"), Consumes("application/json"), Produces("application/json")]
public FileStreamResult? Generate([FromBody] DocumentInfo request,
CancellationToken cancellationToken = default)
Sometime the template property may not be present in serialized query. Then the controller should ignore it. But now I get an error during deserialization that the field is required but missing.
I tried
[DataMember(IsRequired = false)]
but that didn't help me.
How to avoid error at runtime when deserializing?
答案1
得分: 1
> 有时序列化查询中可能没有模板属性。
> 那么控制器应该忽略它。但是现在在反序列化期间出错,提示该字段是必需的,但缺失了。如何在运行时避免错误?
实际上,在忽略序列化时,首先要考虑的是可空性。换句话说,忽略属性应该是 null。因为,如果您将 WhenWritingDefault 或 NullValueHandling.Ignore 设置为非可为空属性,模型绑定器将不会将其忽略,因为它将被视为必需的。因此,评估变得自相矛盾。
此外,为了处理在空属性序列化期间发生的运行时异常,我们需要在 program.cs 文件中明确定义 JsonSerializerOptions 为 WhenWritingNull。
让我们来看看实际操作:
模型:
<!-- language: c# -->
public class DocumentInfo
{
[JsonProperty("FileName", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName("FileName")]
public string FileName { get; set; }
[JsonPropertyName("Template")]
[JsonProperty("Template", NullValueHandling = NullValueHandling.Ignore)]
public string? Template { get; set; }
[Newtonsoft.Json.JsonIgnore]
public string FileExtension => Path.GetExtension(this.FileName);
}
注意: 我通过添加 string?
使 Template 属性可空。
Program.cs:
<!-- language: c# -->
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
输出:
注意: 如果您想了解更多关于在运行时如何忽略所有空值属性的详细信息,可以在此处查看我们的官方文档
英文:
> Sometime the template property may not be present in serialized query.
> Then the controller should ignore it. But now I get an error during
> deserialization that the field is required but missing. How to avoid
> error at runtime when deserializing?
Actually, the first thing you need to consider while ignoring serialization is nullability. In other words, the ignoring property should be null. Because, if you set WhenWritingDefault or NullValueHandling.Ignore to a non nullable property model binder will not ignore that as it will be treated as required. Thus, evaluation became self-contradictory.
In addition, to handle runtime exception during null property serialization we need to explicitely define JsonSerializerOptions as WhenWritingNull in program.cs file.
Let's have a look in practice:
Model:
<!-- language: c# -->
public class DocumentInfo
{
[JsonProperty("FileName", NullValueHandling = NullValueHandling.Ignore)]
[JsonPropertyName("FileName")]
public string FileName { get; set; }
[JsonPropertyName("Template")]
[JsonProperty("Template", NullValueHandling = NullValueHandling.Ignore)]
public string? Template { get; set; }
[Newtonsoft.Json.JsonIgnore]
public string FileExtension => Path.GetExtension(this.FileName);
}
Note: I made Template property as nullable by putting string?
Program.cs:
<!-- language: c# -->
builder.Services.AddControllers().AddJsonOptions(options =>
{
options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
});
Output:
Note: If you would like to know more details how to Ignore all null-value properties during runtime you could check our official document here
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论