Newtonsoft Json.Net序列JObject不忽略空值,即使有正确的设置 [英] Newtonsoft Json.Net serialize JObject doesn't ignore nulls, even with the right settings

查看:4506
本文介绍了Newtonsoft Json.Net序列JObject不忽略空值,即使有正确的设置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用序列Newtonsoft Json.Net的对象。

I'm trying to serialize an object using Newtonsoft Json.Net.

这对象是一个匿名类型充斥着大量的异质的东西,主要是定期波苏斯,但也有一些 JObject s或 JArray 秒。

This object is an anonymous type filled with a lot of heterogenous things, mainly regular POCOs, but also some JObjects or JArrays.

问题是,添加 NullValueHandling 属性时, NullValueHandling.Ignore ,每空属性,都会忽略,但只有当它的常规.NET对象的一部分。在 JObject JArray 仍然存在。

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 ?

推荐答案

A 的价值 JObject 实际上是一个的非空 JValue 的用的 JValue.Type 等于的 JTokenType.Null 。它代表当这种值实际上出现在JSON空的JSON值。我相信它的存在是为了捕捉以下两个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同时出现在 JSON值。在第二种情况下,物业Z不存在。 LINQ到JSON表示与零式首例 JValue ,而不是 JProperty.Value <实际EM >为空的

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 的价值观,用相应的序列化设置,在创建时, JObject

To prevent null tokens from creeping into your JObject's values, use the appropriate serializer setting when creating the JObject:

        var jobj = JObject.FromObject(new
        {
            x = 1,
            y = "bla",
            z = (int?)null
        }, new JsonSerializer { NullValueHandling = NullValueHandling.Ignore } );

这篇关于Newtonsoft Json.Net序列JObject不忽略空值,即使有正确的设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆