How can I exclude an object from serialization that has no fields/properties being serialized in the object.
Below is a simple class as an example.
class Item : IComponent
{
[JsonProperty(PropertyName = "ID", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
public int ID = 0;
}
If I serialize an array of Item objects, I get the following.
{
"Items" : [
{ "$type": "Item" },
{ "$type": "Item", "ID": 1},
{ "$type": "Item", "ID": 2 }
]
}
I want to exclude the first item object in the array because it has no data being saved. Empty "default" objects are useless for my use case. My use case starts with a pre-populated JObject and overlays data when deserializing onto it, so empty objects really are useless.
Any ideas how to exclude objects that have nothing defined in them when serializing? I can't find an ObjectAttribute
or a JsonSerializerSettings
that handles this. I'm okay with doing a ContractResolver
if need be.
Thanks.
Update:
Thanks SANM2009 but the problem with that method is you have to tell the object if it ShouldSerialize. However it needs to be determined at serialization time if everything is set default or is there data set.
Thanks Brian Rogers, I think I can use that (modified a bunch) and make that same concept work in my case.
Update 2:
Brian Rogers example worked great but I had to modify the IsEmpty() method because it didn't take into account empty JObjects with a $type declared.
public static bool IsEmpty(JToken token)
{
return (token.Type == JTokenType.Null) ||
(token.Type == JTokenType.Array && !token.HasValues) ||
(token.Type == JTokenType.Object && !token.HasValues) ||
(token.Type == JTokenType.Object && token.Count() == 1 && token["$type"] != null);
}
Thanks everyone. I was hoping for some simpler like a setting in Json.net but oh well.