我有以下代码:
var data = new {
name = "Jon Doe",
properties = new
{
homes = new Dictionary<string, string>()
},
age = 34
}
var settings = new JsonSerializerSettings {
ContractResolver = new MyResolver()
};
var serializationResult = JsonConvert.SerializeObject(data, settings)
Json.Net合约解析程序MyResolver
定义如下:
class MyResolver : DefaultContractResolver {
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
JsonProperty property = base.CreateProperty(member, memberSerialization);
if (property.PropertyType.GetTypeInfo().IsGenericType &&
typeof(IDictionary).IsAssignableFrom(property.PropertyType.GetGenericTypeDefinition()))
{
property.ShouldSerialize =
instance =>
{
var value = instance.GetType().GetProperty(property.PropertyName).GetValue(instance, null);
return (value as IDictionary).Count > 0;
};
}
return property;
}
}
我的问题是序列化的json结果如下:
{
"name": "Jon Doe",
"properties": {},
"age": 34
}
但是我想摆脱属性"properties": {}
,这意味着我想获得json
{
"name": "Jon Doe",
"age": 34
}
我没有成功地去除这些在移除孩子后导致空白的属性,我怎么能完成这个?
答案 0 :(得分:0)
instance
已经是指定的类型。你可以简单地演员:
instance =>
{
var value = (IDictionary)instance;
return value != null && value.Keys.Count() > 0
};
尝试是否有效。如果没有,请检查调试value
的内容是什么,然后回发。