我使用Json.Net库进行血清化。
这是我的代码:
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
namespace ConsoleApp
{
internal class Program
{
private static void Main(string[] args)
{
var field1 = new Field();
field1.ExtraFields = new Dictionary<string, JToken>();
var field2 = new Field();
field1.ExtraFields = new Dictionary<string, JToken>();
var panelRow1 = new PanelRow();
panelRow1.Fields = new List<Field>();
var panelRow2 = new PanelRow();
panelRow2.Fields = new List<Field>();
var row1 = new Row();
row1.PanelRows = new List<PanelRow>();
row1.PanelRows.Add(panelRow1);
row1.PanelRows.Add(panelRow2);
var row2 = new Row();
row2.PanelRows = new List<PanelRow>();
row2.PanelRows.Add(panelRow1);
row2.PanelRows.Add(panelRow2);
var baseForm = new BaseForm();
baseForm.Rows = new List<Row>();
baseForm.Rows.Add(row1);
baseForm.Rows.Add(row2);
var result = JsonConvert.SerializeObject(baseForm, Formatting.Indented, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Console.ReadKey(true);
}
}
class BaseForm
{
[JsonProperty(PropertyName = "rows")]
public IList<Row> Rows { get; set; }
public bool ShouldSerializeRows()
{
return Rows.Count != 0;
}
}
class Row
{
[JsonProperty(PropertyName = "panels")]
public IList<PanelRow> PanelRows { get; set; }
public bool ShouldSerializePanelRows()
{
return PanelRows.Count != 0;
}
}
class PanelRow
{
[JsonProperty(PropertyName = "fields")]
public IList<Field> Fields { get; set; }
public bool ShouldSerializeFields()
{
return Fields.Count != 0;
}
}
class Field
{
[JsonExtensionData]
public IDictionary<string, JToken> ExtraFields { get; set; }
public bool ShouldSerializeExtraFields()
{
return ExtraFields.Count != 0;
}
}
}
序列化后,我在数组中有空对象:
我在这种情况下的结果必须是这样的:
{}
因为我们在较低元素&#39; Field&#39;中没有任何信息。
如何解决该问题,从Json结果中删除空对象?
提前致谢。