I want to remove all null properties in a generic object. It doesn’t have to be recursive, one level deep is also fine.
The reason I need is for a custom JavascriptConvertor implementation for JSON serialization which gives me: {“Name”:”Aleem”, “Age”:null, “Type”:”Employee”}
And I would like to skip over the null object.
The function for this task takes in the objct and returns a Dictionary:
IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
So I would like to remove all null properties from obj. All properties have getter but if the property is not set, the getter returns null.
You can implement your own JavaScriptConverter to handle serialization of your type. Then you get full control on how properties are serialized.
@Richards answer provides a nice implementation of the Serialize method.
The Deserialize method would be quite similar but I’ll leave the implementation up to you. Now the only drawback with JavaScriptConverter is that it has to get the supported types from somewhere. Either hardcode it like this:
…or make it configurable, e.g. via the class constructor.