这个问题在这里已经有了答案:
How to omit/ignore/skip empty object literals in the produced JSON?
(3 个回答)
4年前关闭。
我试图序列化一组包含各种类型的对象,包括对其他自定义类型的对象引用。我希望这些对象引用在其属性成员都是默认值或 null 时被排除。这是设置:
public class ObjectA
{
[DefaultValue(2)]
[JsonProperty(PropertyName = "propertyA")]
public int PropertyA { get; set; } = 6;
[JsonProperty(PropertyName = "objectB")]
public ObjectB ObjectB { get; set; } = new ObjectB();
}
public class ObjectB
{
[DefaultValue(2)]
[JsonProperty(PropertyName = "propertyA")]
public int PropertyA { get; set; } = 2;
[JsonProperty(PropertyName = "propertyB")]
public string PropertyB { get; set; }
}
问题是,当我使用以下内容序列化 ObjectA 时:
var settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
settings.DefaultValueHandling = DefaultValueHandling.Ignore;
return JsonConvert.SerializeObject(ObjectA, settings);
我想看这个:
{
"propertyA": 6
}
但是我仍然看到一个空的对象属性引用:
{
"propertyA": 6,
"objectB" : {}
}
我想摆脱 json 中的 objectB,并且只有当它的成员之一不是默认值或 null 时才显示它。虽然此示例仅显示了一层嵌套,但它需要适用于任何级别的对象嵌套。
最佳答案
问题在于 ObjectB
的默认值本身是一个对象,而不是序列化时它具有的属性的默认值 ObjectA
.
如果您查看示例 here ,他们提到了 nullable
的预期默认值类型和 object
s 即 null
This option will ignore all default values (e.g. null for objects and nullable types; 0 for integers, decimals and floating point numbers; and false for booleans).
为了说明它的含义,请尝试序列化
ObjectB
使用默认值 -var objectB = new ObjectB
{
PropertyA = 2 //The default value is also 2.
};
string serialized = JsonConvert.SerializeObject(objectB,
Newtonsoft.Json.Formatting.Indented,
new JsonSerializerSettings {
DefaultValueHandling = DefaultValueHandling.Ignore
});
你得到的是
{}
.现在,如果您明确设置
ObjectB
至 null
,只有这样序列化程序才会将其忽略为 object
总体上 -var objectA = new ObjectA
{
PropertyA = 6,
ObjectB = null
};
string serialized = JsonConvert.SerializeObject(objectA,
Newtonsoft.Json.Formatting.Indented,
new JsonSerializerSettings {
DefaultValueHandling = DefaultValueHandling.Ignore
});
你会得到预期的结果 -
{
"propertyA": 6
}
您可以尝试不同的值,看看这是否满足您的期望。
关于c# - Newtonsoft.Json CustomContractResolver 排除空对象节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43360141/