# Conditionally serializing fields using Jackson

|

When interacting with some REST API, we often deal with serialization of Java objects to JSON strings. Lately, I came across a requirement to conditionally skip an object’s field, according to its value. Assume, for example, the following class:

Assume we’d like to include value in the JSON serialized string only if its value is not equal to 0. I’m using Jackson for JSON serialization, and the solution, as I found, was to implement and register a PropertyFilter:

In my case, only the first method required an special implementation:

I also had to annotate the class with the required filter:

Lastly, upon creating an ObjectMapper to be used for JSON serialization, the filter should be registered:

We can now test the object mapper to see the filtering working: