如何在运行时反序列化 ASP.NET Core 应用程序中忽略属性

huangapple go评论67阅读模式
英文:

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(&quot;Template&quot;)]
    [JsonProperty(&quot;Template&quot;, NullValueHandling = NullValueHandling.Ignore)]
    public string? Template { get; set; }
    [Newtonsoft.Json.JsonIgnore]
    public string FileExtension =&gt; Path.GetExtension(this.FileName);
}

注意: 我通过添加 string? 使 Template 属性可空。

Program.cs:

<!-- language: c# -->
builder.Services.AddControllers().AddJsonOptions(options =>
{

    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;

});

输出:

如何在运行时反序列化 ASP.NET Core 应用程序中忽略属性

注意: 如果您想了解更多关于在运行时如何忽略所有空值属性的详细信息,可以在此处查看我们的官方文档

英文:

> 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(&quot;Template&quot;)]
        [JsonProperty(&quot;Template&quot;, NullValueHandling = NullValueHandling.Ignore)]
        public string? Template { get; set; }
        [Newtonsoft.Json.JsonIgnore]
        public string FileExtension =&gt; 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:

如何在运行时反序列化 ASP.NET Core 应用程序中忽略属性

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

huangapple
  • 本文由 发表于 2023年4月7日 02:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952775.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定