首页 > 解决方案 > 使用新的 Net Core 3.0 Json 时忽略属性

问题描述

在 ASP.Net Core 2.2 中使用 JSON.Net 时,我能够在序列化为 JSON 时忽略其值为 null 的属性:

[JsonProperty(NullValueHandling = NullValueHandling.Ignore)]
public DateTime? Created { get; set; }

但是,当使用 JSON (System.Text.Json) 中内置的新 ASP.Net Core 3.0 时,如果其值为 null,我找不到忽略属性的等效属性。

我只能找到 JsonIgnore。

我错过了什么吗?

标签: jsonjson.netasp.net-core-3.0.net-core-3.0system.text.json

解决方案


我正在查看.Net Core 3.1,这应该忽略空值

    services.AddControllers().AddJsonOptions(options =>
    {
        options.JsonSerializerOptions.IgnoreNullValues = true;
    });

请注意,以上不是每个属性/属性,尽管有一个属性可能有用JsonIgnoreAttribute

解决您的问题的替代方法可能是JsonConverterAttribute,有关如何编写自己的转换器的信息在这里


推荐阅读