简体   繁体   中英

Custom JSON fields with Jackson in response

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?

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

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

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 {
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM