Reputation:
I have a class with a lot of properties, many of them can have null value. I am serializing this class using JSON.NET and I would like to leave out those properties with null value.
For property per property basis I could do:
public class MyClass
{
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
object property1;
.
.
.
[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
object property346;
}
But this is very tedious, hard to maintain and reduces readability. Is there a way to set annotation on a whole class making it ignore properties with null values while serializing. I do want to be able to do that via annotations and not in code.
Upvotes: 1
Views: 642
Reputation: 5877
Reading the documentation, it does not seem that JsonObjectAttribute
offers a way to do this. However, you can add your configuration to an extension method, which changes serialization settings depending on the object being serialized.
public static string ToJsonString(this object obj)
{
Type[] objectWithoutNulls = { typeof(MyClass) };
bool isWithoutNulls = objectWithoutNulls.Contains(obj.GetType());
if (isWithoutNulls)
{
return JsonConvert.SerializeObject(obj, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
}
else
{
return JsonConvert.SerializeObject(obj);
}
}
Then you can use it on all objects like:
var myClass = new MyClass();
var myObject = new Object();
var myClassJson = myClass.ToJsonString(); // Will remove nulls.
var myObjectJson = myObject.ToJsonString(); // Will not remove nulls.
Now you have a single place where you can add your configuration for all objects.
Upvotes: 1