我有这样的课程:
public class Province
{
public string name { get; set; }
public List<Province> Cities { get; set; }
public virtual Province parent { get; set; }
public Province()
{
Cities = new List<Province>();
}
}
我有这个类的列表,我希望将它转换为Json,我使用了这个代码并且很好:
string output= JsonConvert.SerializeObject(provinces, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
我的结果如下:
[{"name":"ProvinceName","Cities":[{"name":"CityName","Cities":[]}],"parent":null},
我想删除没有任何孩子的城市Key:
[{"name":"ProvinceName","Cities":[{"name":"CityName"}],"parent":null},
我该怎么做?
答案 0 :(得分:3)
您可以使用DefaultValueHandling
和NullValueHandling
。看看这个page和示例(如果您的列表不在构造函数中初始化,这将有效)。或者,您可以编写自己的转换器来执行其他操作,这些操作无法立即使用。
以下是此page的修改后的示例。这段代码应该做你想要的。但是,我还没有测试过它。
public class ShouldSerializeContractResolver : DefaultContractResolver
{
public new static readonly ShouldSerializeContractResolver Instance = new ShouldSerializeContractResolver();
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.DeclaringType == typeof(List<Province>) && property.PropertyName == "Cities")
{
property.ShouldSerialize =
instance =>
{
Province province = (Province)instance;
return province.Cities != null && province.Cities.Count > 0;
};
}
return property;
}
}
序列化对象时,请指定此合约解析程序。
string json = JsonConvert.SerializeObject(
provinces,
Formatting.None,
new JsonSerializerSettings
{
ContractResolver = new ShouldSerializeContractResolver()
});