方法一:
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
JObject testJson = new JObject()
{
{ "code", "1234560" },
{ "app", null }
};
testJson.DescendantsAndSelf()
.OfType<JProperty>()
.Where(p => p.Value.Type == JTokenType.Null || p.Value.ToString() == "")
.ToList()
.ForEach(p => p.Remove());
方法二:
直接调用方法即可
private static void RemoveEmptyValues(JToken token)
{
if (token is JValue)
{
if (token.Type == JTokenType.Null || (token.Type == JTokenType.String && token.ToString() == ""))
{
token.Parent.Remove();
}
}
else if (token is JContainer)
{
foreach (JToken child in token.Children().ToList())
{
RemoveEmptyValues(child);
}
if (!token.HasValues)
{
token.Parent.Remove();
}
}
}
方法三:
直接调用方法即可
public static JToken RemoveEmptyValues(JToken token)
{
if (token.Type == JTokenType.Object)
{
JObject obj = (JObject)token;
List<string> keysToRemove = new List<string>();
foreach (JProperty prop in obj.Properties())
{
JToken propValue = RemoveEmptyValues(prop.Value);
if (propValue.Type == JTokenType.Null ||
propValue.Type == JTokenType.String && ((string)propValue).Trim() == "" ||
propValue.Type == JTokenType.Array && !propValue.HasValues ||
propValue.Type == JTokenType.Object && !((JObject)propValue).HasValues)
{
keysToRemove.Add(prop.Name);
}
else
{
prop.Value = propValue;
}
}
foreach (string key in keysToRemove)
{
obj.Remove(key);
}
return obj;
}
else if (token.Type == JTokenType.Array)
{
JArray arr = (JArray)token;
List<JToken> itemsToRemove = new List<JToken>();
for (int i = 0; i < arr.Count; i++)
{
JToken item = RemoveEmptyValues(arr[i]);
if (item.Type == JTokenType.Null ||
item.Type == JTokenType.String && ((string)item).Trim() == "" ||
item.Type == JTokenType.Array && !item.HasValues ||
item.Type == JTokenType.Object && !((JObject)item).HasValues)
{
itemsToRemove.Add(arr[i]);
}
else
{
arr[i] = item;
}
}
foreach (JToken item in itemsToRemove)
{
arr.Remove(item);
//item.RemoveFromLowestPossibleParent();
}
return arr;
}
// 对于其他类型的JToken(如原始值),直接返回原始token
return token;
}
方法四:
仅针对于有对应实体类的JSON序列化
public class Person
{
public string Name { get; set; }
public int? Age { get; set; }
}
static void Main(string[] args)
{
Person person = new Person()
{
Name = "Test",
Age = null
};
var setting = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore
};
string str = JsonConvert.SerializeObject(person, setting);
}
标签:C#,JTokenType,token,JToken,item,JSON,propValue,Type,节点
From: https://www.cnblogs.com/waou/p/18286158