雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

.NET Core Razor page/MVC 返回json忽略空属性

2024-10-13 19

.NET Core Razor page/MVC 返回json忽略空属性,修改program.cs。

添加配置

builder.Services.AddRazorPages()

.AddJsonOptions(options => {

    options.JsonSerializerOptions.DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull;

});

这个options里的DefaultIgnoreCondition枚举包含如下设置:

//
    // 摘要:
    //     Controls how the System.Text.Json.Serialization.JsonIgnoreAttribute ignores properties
    //     on serialization and deserialization.
    public enum JsonIgnoreCondition
    {
        //
        // 摘要:
        //     Property will always be serialized and deserialized, regardless of System.Text.Json.JsonSerializerOptions.IgnoreNullValues
        //     configuration.
        Never,
        //
        // 摘要:
        //     Property will always be ignored.
        Always,
        //
        // 摘要:
        //     Property will only be ignored if it is null.
        WhenWritingDefault,
        //
        // 摘要:
        //     If the value is null, the property is ignored during serialization. This is applied
        //     only to reference-type properties and fields.
        WhenWritingNull
    }

这样就可以在输入Json的时候忽略null值了。

更新于:5天前
赞一波!

文章评论

评论问答