3

I have an Object like this:

public class MyObject {
    private String name;
    private int number;
    // ...
}

And I want to include the number only if the value is not negative (number >= 0).

While researching I found Jackson serialization: ignore empty values (or null) and Jackson serialization: Ignore uninitialised int. Both are using the @JsonInclude annotation with either Include.NON_NULL, Include.NON_EMPTY or Include.NON_DEFAULT, but none of them fits my problem.

Can I somehow use @JsonInclude with my condition number >= 0 to include the value only if not negative? Or is there another solution how I can achieve that?

Samuel Philipp
  • 10,631
  • 12
  • 36
  • 56
  • 1
    As you would normally convert the object jackson converted into another object (it's external data and its good practice to convert external data into your own data structures to not rely on them in your business logic) I would suggest you to implement the outlined logic in the conversion process as jackson should not be used to implement logic that is specific to your application and thus your business logic. You may be able to achieve this but then you coupled application specific logic to your json mapper. – roookeee Jun 07 '19 at 11:54

1 Answers1

4

If you use Jackson 2.9+ version, you could try with a Include.Custom value for @JsonInclude.
From the JsonInclude.CUSTOM specification :

Value that indicates that separate filter Object (specified by JsonInclude.valueFilter() for value itself, and/or JsonInclude.contentFilter() for contents of structured types) is to be used for determining inclusion criteria. Filter object's equals() method is called with value to serialize; if it returns true value is excluded (that is, filtered out); if false value is included.

That is a more specific and declarative approach than defining a custom serializer.

@JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = PositiveIntegerFilter.class)
private int number;

// ...
public class PositiveIntegerFilter {
    @Override
    public boolean equals(Object other) {
       // Trick required to be compliant with the Jackson Custom attribute processing 
       if (other == null) {
          return true;
       }
       int value = (Integer)other;
       return value < 0;
    }
}

It works with objectsand primitives and it boxes primitives to wrappers in the filter.equals() method.

davidxxx
  • 125,838
  • 23
  • 214
  • 215