1

I have some RESTful WS created with Spring Boot and one of some endpoint's methods returns instance of some class which will be converted then into JSON using embedded Jackson library. Jackson converts to JSON every field, even if some fields are null. So in the output it will look like:

{
    "field1": "res1",
    "field2": "res2",
    "field3": null
}

I want to ignore some field it the output in particular cases. Not everytime, at some cases. How to do it?

catscoolzhyk
  • 675
  • 10
  • 29

3 Answers3

3

To suppress serializing properties with null values using Jackson >2.0, you can configure the ObjectMapper directly, or make use of the @JsonInclude annotation:

mapper.setSerializationInclusion(Include.NON_NULL);

or:

@JsonInclude(Include.NON_NULL)
class Foo
{
  String field1;
  String field2;
  String field3;
}

Alternatively, you could use @JsonInclude in a getter so that the attribute would be shown if the value is not null.

Complete example available at How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

surendrapanday
  • 770
  • 2
  • 9
  • 24
1

To exclude null values you can use

@JsonInclude(value = Include.NON_NULL)
public class YourClass {
}

And to include customised values you can use

public class Employee {
  private String name;
  @JsonInclude(value = JsonInclude.Include.CUSTOM, valueFilter = DateOfBirthFilter.class)
  private Date dateOfBirth;
  @JsonInclude(content = JsonInclude.Include.CUSTOM, contentFilter = PhoneFilter.class)
  private Map<String, String> phones;
}

public class DateOfBirthFilter {

  @Override
  public boolean equals(Object obj) {
      if (obj == null || !(obj instanceof Date)) {
          return false;
      }
      //date should be in the past
      Date date = (Date) obj;
      return !date.before(new Date());
  }
}

public class PhoneFilter {
  private static Pattern phonePattern = Pattern.compile("\\d{3}-\\d{3}-\\d{4}");

  @Override
  public boolean equals(Object obj) {
      if (obj == null || !(obj instanceof String)) {
          return false;
      }
      //phone must match the regex pattern
      return !phonePattern.matcher(obj.toString()).matches();
  }
}

Took reference from https://www.logicbig.com/tutorials/misc/jackson/json-include-customized.html

Pooja Aggarwal
  • 1,163
  • 6
  • 14
0

At the top your class add the NON_NULL Jackson annotation to ignore null values when receiving or sending

@JsonInclude(value = Include.NON_NULL)
public class SomeClass {
}
Vaibhav Gupta
  • 638
  • 4
  • 12