Использовать JsonInclude
аннотацию.Пример:
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
public static void main(String[] args) throws Exception {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(Include.NON_NULL);
System.out.println(mapper.writeValueAsString(new User()));
}
}
@JsonInclude
class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Над кодом напечатаны:
{"name":null}
Значение по умолчанию в JsonInclude
равно ALWAYS
:
/**
* Inclusion rule to use for instances (values) of types (Classes) or
* properties annotated.
*/
public Include value() default Include.ALWAYS;
Другой вариант - использовать JsonSerialize
аннотация:
@JsonSerialize(include = Inclusion.ALWAYS)
class User {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Результат такой же, как для JsonInclude
.