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

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

问题描述

我有一些数据必须序列化为 JSON.我正在使用 JSON.NET.我的代码结构是这样的:

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 输出只需要 Field1 OR Field2 OR Field3 - 这取决于使用哪个字段(即不是空值).默认情况下,我的 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.

但是因为结构是值类型,您需要标记 Field2, Field3 nullable 以获得预期结果:

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.

文档:NullValueHandling 枚举

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

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