2

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.

  • 1
    Possible duplicate of [Excluding specific items in a collection when serializing to JSON](https://stackoverflow.com/questions/20955722/excluding-specific-items-in-a-collection-when-serializing-to-json) – SANM2009 Feb 14 '18 at 21:49
  • You may find the `RemoveEmptyChildren` method presented in [*JSON.NET serialize JObject while ignoring null properties*](https://stackoverflow.com/q/33027409/10263) to be of use here. – Brian Rogers Feb 14 '18 at 22:39

1 Answers1

1

Isn't it better filtering the objects after serializing them?

Items.Where(t => t.GetType().GetProperty("ID")!=null));
Hichame Yessou
  • 2,658
  • 2
  • 18
  • 30
  • 1
    I don't want empty objects serialized at all. However maybe I could filter them out OnSerializing instead... hmmm. Dang though I need that [OnSerialzing] on every object to handle the case... – David Hietpas Feb 15 '18 at 14:56
  • There is a problem in particular for not serializing empty object at all? (just curious) – Hichame Yessou Feb 22 '18 at 13:43