[英]JSON.NET serialize array with empty string for default values
像這樣的數組:
var arr = new object[] {0, string.Empty, null};
由JSON.NET序列化為:
[0,“”,空]
我需要強制JSON.NET獲得下一個結果(類型默認值根本沒有值):
[,,]
有什么辦法可以存檔嗎?
public static class JsonHelper
{
public static string SerializeToMinimalJson(object obj)
{
return JToken.FromObject(obj).RemoveEmptyChildren().ToString();
}
public static JToken RemoveEmptyChildren(this 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 = child.RemoveEmptyChildren();
}
if (!child.IsNullOrEmpty())
{
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 = child.RemoveEmptyChildren();
}
if (!child.IsNullOrEmpty())
{
copy.Add(child);
}
}
return copy;
}
return token;
}
public static bool IsNullOrEmpty(this JToken token)
{
return token == null ||
(token.Type == JTokenType.Array && !token.HasValues) ||
(token.Type == JTokenType.Object && !token.HasValues) ||
(token.Type == JTokenType.String && token.ToString() == String.Empty) ||
(token.Type == JTokenType.Null);
}
}
上課將刪除空孩子。 然后,您可以像這樣序列化您的對象:
var json = JsonHelper.SerializeToMinimalJson(obj);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.