使用新的Net Core 3.0 Json忽略属性为null时 [英] Ignore property when null using the new Net Core 3.0 Json

查看:506
本文介绍了使用新的Net Core 3.0 Json忽略属性为null时的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在ASP.Net Core 2.2中使用JSON.Net时,当序列化为JSON时,如果其值为null,我就可以忽略该属性:

When using JSON.Net in ASP.Net Core 2.2 I was able to ignore a property when its value was null when serializing to JSON:

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

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

But when using the new ASP.Net Core 3.0 built in JSON (System.Text.Json) I can’t find an equivalent attribute to ignore a property if its value is null.

我只能找到JsonIgnore.

I could only find JsonIgnore.

我想念什么吗?

推荐答案

我正在查看.Net Core 3.1,该位置应忽略null值

I'm looking at .Net Core 3.1, where this should ignore null values

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

注意,以上内容不是针对每个属性/属性的,尽管有一个属性可能会有所帮助

Note, the above isn't per property/attribute, although there is an attribute which may be helpful JsonIgnoreAttribute

另一种解决问题的方法可能是此处

An alternative, to solve your problem might be a JsonConverterAttribute, information on how to write your own converter is here

这篇关于使用新的Net Core 3.0 Json忽略属性为null时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆