您可以使用一种类似于下面的递归帮助器方法来在序列化之前
null从
JToken层次结构中删除值。
using System;using Newtonsoft.Json.Linq;public static class JsonHelper{ public static JToken RemoveEmptyChildren(JToken token) { if (token.Type == JTokenType.Object) { JObject copy = new JObject(); foreach (JProperty prop in token.Children<JProperty>()) { JToken child = prop.Value; if (child.HasValues) { child = RemoveEmptyChildren(child); } if (!IsEmpty(child)) { copy.Add(prop.Name, child); } } return copy; } else if (token.Type == JTokenType.Array) { JArray copy = new JArray(); foreach (JToken item in token.Children()) { JToken child = item; if (child.HasValues) { child = RemoveEmptyChildren(child); } if (!IsEmpty(child)) { copy.Add(child); } } return copy; } return token; } public static bool IsEmpty(JToken token) { return (token.Type == JTokenType.Null); }}演示:
string json = @"{ ""Foo"": { ""P1"": null, ""P2"": ""hello world"", ""P3"": null, ""P4"": { ""P1"": 1, ""P2"": null, ""P3"": null }, ""FooArray"": [ { ""F1"": null, ""F2"": null, ""F3"": null } ] }, ""Bar"": null}";JToken token = JsonHelper.RemoveEmptyChildren(JToken.Parse(json));Console.WriteLine(token.ToString(Formatting.Indented));输出:
{ "Foo": { "P2": "hello world", "P4": { "P1": 1 }, "FooArray": [ {} ] }}小提琴:https :
//dotnetfiddle.net/wzEOie
请注意,删除所有空值后,您可能会在中有一个空对象
FooArray,您可能不需要。(如果删除了该对象,则
FooArray可能会有一个空值,您可能也不想这样做。)如果要使helper方法在删除它时更加主动,则可以将IsEmpty函数更改为:
public static bool IsEmpty(JToken token) { return (token.Type == JTokenType.Null) || (token.Type == JTokenType.Array && !token.HasValues) || (token.Type == JTokenType.Object && !token.HasValues); }进行适当的更改后,您的输出将如下所示:
{ "Foo": { "P2": "hello world", "P4": { "P1": 1 } }}小提琴:https://dotnetfiddle.net/ZdYogJ



