Reputation: 303
I have class like this :
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>();
}
}
and I have list of this class and I want convert this to Json , I used this code and its nice :
string output= JsonConvert.SerializeObject(provinces, Formatting.None,
new JsonSerializerSettings()
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
my result is like belowe :
[{"name":"ProvinceName","Cities":[{"name":"CityName","Cities":[]}],"parent":null},
I want to remove cities Key which dont have any child like :
[{"name":"ProvinceName","Cities":[{"name":"CityName"}],"parent":null},
how Can I do this ?
Upvotes: 1
Views: 378
Reputation: 305
You can use DefaultValueHandling
and NullValueHandling
. Take a look at this page and examples (this would work if your list would not be initialized in the constructor). Alternatively, you can write your own converter to do other things, which are not available out of the box.
Here is a modified sample from this page. This code should do what you want. However, I have not tested it.
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;
}
}
When serializing your object specify this contract resolver.
string json = JsonConvert.SerializeObject(
provinces,
Formatting.None,
new JsonSerializerSettings
{
ContractResolver = new ShouldSerializeContractResolver()
});
Upvotes: 3