忽略Json.net空字段字段、Json、net

2023-09-04 00:05:01 作者:电量君你别走

我有,我要序列化到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.

文件:NullValueHandling枚举

 
精彩推荐
图片推荐