I have the following code:
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)
The Json.Net contract resolver MyResolver
is defined as follow:
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;
}
}
My problem is that the json result of the serialization is the following:
{
"name": "Jon Doe",
"properties": {},
"age": 34
}
but I would like to get rid of the property "properties": {}
, which means that I would like to obtain the json
{
"name": "Jon Doe",
"age": 34
}
I have done unsuccessful attempts to get rid of these kind of properties that result to be empty after removing their childs, how could I accomplish this?