忽略Json.net中的空字段


71

我有一些必须序列化为JSON的数据。我正在使用JSON.NET。我的代码结构与此类似:

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

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

问题是,我的JSON输出需要具有ON Field1ORField2或ON-Field3取决于所使用的字段(即不为null)。默认情况下,我的JSON如下所示:

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

我知道我可以使用NullValueHandling.Ignore,但这给了我如下所示的JSON:

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

我需要的是:

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

有没有简单的方法可以做到这一点?


Answers:



75

您还可以将JsonProperty属性应用于相关属性,并以这种方式设置空值处理。请参考Reference以下示例中的属性:

注意:JsonSerializerSettings会覆盖属性。

public class Person
{
    public int Id { get; set; }

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

    public string Name { get; set; }
}

Hth。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.