问题描述
我正在尝试使用 Newtonsoft Json.Net 序列化对象.
I'm trying to serialize an object using Newtonsoft Json.Net.
这个对象是一个匿名类型,里面填充了很多异构的东西,主要是常规的POCO,也有一些JObject
s或者JArray
s.
This object is an anonymous type filled with a lot of heterogenous things, mainly regular POCOs, but also some JObject
s or JArray
s.
问题是,当将 NullValueHandling
属性添加到 NullValueHandling.Ignore
时,每个 null 属性都会被忽略,但前提是它是常规".Net 对象的一部分.JObject
或 JArray
中的每个 null 属性都会保留.
The thing is that when adding the NullValueHandling
property to NullValueHandling.Ignore
, every null property gets ignored, but only if it's part of a "regular" .Net object. Every null property inside a JObject
or JArray
remains.
这是一个最小的例子:
var jobj = JObject.FromObject(new Anything{
x = 1,
y = "bla",
z = null
});
var poco = new Foo {
foo1 = "bar",
foo2 = null
};
var serialized = JsonConvert.SerializeObject(new {
source1 = poco,
source2 = jobj
}, Newtonsoft.Json.Formatting.None, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore});
是否有一种简单的方法也可以忽略这些空值?我错过了一些设置选项吗?还是我必须手动处理?
Is there a simple way to ignore those null values as well ? Did I miss some setting option ? Or do I have to deal with it manually ?
推荐答案
JObject
中的"null"
值实际上是一个非空JValue
与 JValue.Type代码> 等于
JTokenType.Null
.当 JSON 中实际出现这样的值时,它表示 JSON 值 null.我相信它的存在是为了捕捉以下两个 JSON 对象之间的差异:
A "null"
value in a JObject
is actually a non-null JValue
with JValue.Type
equal to JTokenType.Null
. It represents a JSON value of null when such a value actually appears in the JSON. I believe it exists to capture the difference between the following two JSON objects:
"source2": {
"z": null
}
"source2": {
}
在第一种情况下,属性 "z"
带有 null
JSON 值.在第二种情况下,属性 "z"
不存在.Linq-to-JSON 表示第一个具有空类型 JValue
的情况,而不是 JProperty.Value
实际上 为空.
In the first case, the property "z"
is present with a null
JSON value. In the second case, the property "z"
is not present. Linq-to-JSON represents the first case with a null-type JValue
rather than having JProperty.Value
actually be null.
为防止空标记进入您的 JObject
的值,请在从某些 POCO 创建 JObject
时使用适当的序列化程序设置:
To prevent null tokens from creeping into your JObject
's values, use the appropriate serializer setting when creating the JObject
from some POCO:
var jobj = JObject.FromObject(new
{
x = 1,
y = "bla",
z = (int?)null
}, new JsonSerializer { NullValueHandling = NullValueHandling.Ignore } );
(注意 POCO 本身不能是 JObject
.无类型方法 JsonConvert.DeserializeObject(jsonString)
或 JsonConvert.DeserializeObject
在 jsonString
中的根 JSON 容器是 JSON 对象时默认返回 JObject
.)
(Note the POCO must not itself already be a JObject
. The untyped method(s) JsonConvert.DeserializeObject(jsonString)
or JsonConvert.DeserializeObject<dynamic>(jsonString)
will by default return a JObject
when root JSON container in jsonString
is a JSON object.)
这篇关于Newtonsoft Json.Net 序列化 JObject 不会忽略空值,即使设置正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!