C# 忽略 Json.net 中的空字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9819640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ignoring null fields in Json.net
提问by Thaven
I have some data that I have to serialize to JSON. I'm using JSON.NET. My code structure is similar to this:
我有一些必须序列化为 JSON 的数据。我正在使用 JSON.NET。我的代码结构类似于:
public struct structA
{
public string Field1;
public structB Field2;
public structB Field3;
}
public struct structB
{
public string Subfield1;
public string Subfield2;
}
Problem is, my JSON output needs to have ONLY Field1OR Field2OR Field3- it depends on which field is used (i.e. not null).
By default, my JSON looks like this:
问题是,我的 JSON 输出需要有 ONLY Field1OR Field2OR Field3- 这取决于使用哪个字段(即不为空)。默认情况下,我的 JSON 如下所示:
{
"Field1": null,
"Field2": {"Subfield1": "test1", "Subfield2": "test2"},
"Field3": {"Subfield1": null, "Subfield2": null},
}
I know I can use NullValueHandling.Ignore, but that gives me JSON that looks like this:
我知道我可以使用NullValueHandling.Ignore,但这给了我看起来像这样的 JSON:
{
"Field2": {"Subfield1": "test1", "Subfield2": "test2"},
"Field3": {}
}
And what I need is this:
我需要的是这个:
{
"Field2": {"Subfield1": "test1", "Subfield2": "test2"},
}
Is there simple way to achieve this?
有没有简单的方法来实现这一目标?
采纳答案by nemesv
Yes you need to use JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore.
是的,您需要使用JsonSerializerSettings.NullValueHandling = NullValueHandling.Ignore.
But because structs are value typesyou need to mark Field2, Field3 nullableto get the expected result:
但是由于结构是值类型,您需要将 Field2、Field3 标记为可为空以获得预期结果:
public struct structA
{
public string Field1;
public structB? Field2;
public structB? Field3;
}
Or just use classes instead of structs.
或者只是使用类而不是结构。
Documentation: NullValueHandling Enumeration
回答by Jaans
You can also apply the JsonProperty attribute to the relevant properties and set the null value handling that way. Refer to the Referenceproperty in the example below:
您还可以将 JsonProperty 属性应用到相关属性并以这种方式设置空值处理。请参阅Reference以下示例中的属性:
Note: The JsonSerializerSettingswill override the attributes.
注意:JsonSerializerSettings将覆盖属性。
public class Person
{
public int Id { get; set; }
[JsonProperty( NullValueHandling = NullValueHandling.Ignore )]
public int? Reference { get; set; }
public string Name { get; set; }
}
Hth.
嗯。

