忽略Json.net空字段 [英] Ignoring null fields in Json.net

查看:372
本文介绍了忽略Json.net空字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有,我要序列化到JSON的一些数据。我使用JSON.NET。我的code结构是类似这样的:

I have some data that I have to serialize to JSON. I'm using JSON.NET. My code structure is similar to this:

public struct structA
{
    public string Field1;
    public structB Field2;
    public structB Field3;
}

public struct structB
{
    public string Subfield1;
    public string Subfield2;
}

但问题是,我的JSON输出需要只有字段1 字段2 字段3 - 这取决于哪个字段使用(即不为空)。 默认情况下,我的JSON是这样的:

Problem is, my JSON output needs to have ONLY Field1 OR Field2 OR Field3 - it depends on which field is used (i.e. not null). By default, my JSON looks like this:

{
    "Field1": null,
    "Field2": {"Subfield1": "test1", "Subfield2": "test2"},
    "Field3": {"Subfield1": null, "Subfield2": null},
}

我知道我可以使用 NullValueHandling.Ignore ,但是给我的JSON看起来是这样的:

I know I can use NullValueHandling.Ignore, but that gives me JSON that looks like this:

{
    "Field2": {"Subfield1": "test1", "Subfield2": "test2"},
    "Field3": {}
}

和我需要的是这样的:

{
    "Field2": {"Subfield1": "test1", "Subfield2": "test2"},
}

有没有简单的方法来实现这一目标?

Is there simple way to achieve this?

推荐答案

是的,你需要使用 JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore

但由于结构是值类型你需要标志字段2,字段3 可空,以获得期望的结果:

But because structs are value types you need to mark Field2, Field3 nullable to get the expected result:

public struct structA
{
    public string Field1;
    public structB? Field2;
    public structB? Field3;
}

或者只是使用的,而不是结构类。

Or just use classes instead of structs.

文件:<一href="http://www.newtonsoft.com/json/help/html/T_Newtonsoft_Json_NullValueHandling.htm">NullValueHandling枚举

这篇关于忽略Json.net空字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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