Java POJO文件空值更改为默认预定义值

时间:2016-03-19 07:33:10

标签: java spring maven

这是我正在使用的POJO文件 @JsonInclude(JsonInclude.Include.NON_EMPTY)用于删除空值。

此处"university" : "" -空值

当前输出,(杰克逊删除该字段)

{ "id" : 1, "user_id" : 1, "education" : "s adfsdsd fsdfad", "institute" : "fsdf", "date_from" : "2014-01-01 00:00:00.0", "date_to" : "2011-03-01 00:00:00.0" }

但我需要输出(而不是null我需要 - 未定义)

{ "id" : 1, "user_id" : 1, "education" : "s adfsdsd fsdfad", "institute" : "fsdf", **"university" : "not_defined"**, "date_from" : "2014-01-01 00:00:00.0", "date_to" : "2011-03-01 00:00:00.0" }


import com.fasterxml.jackson.annotation.JsonInclude;

/**
 * Created by gopu on 18/3/16.
 */
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class UserEducation {

    private long id;
    private int user_id;
    private String education, institute, university, date_from, date_to;

    public UserEducation(long id, int user_id,  String education, String institute, String university, String date_from, String date_to) {
        this.id = id;

1 个答案:

答案 0 :(得分:1)

您必须自己编写JsonSerializer才能完成此任务:

class MySerializer extends JsonSerializer<String> {
    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers)
        throws IOException, JsonProcessingException {

        gen.writeString("not_defined");
    }
}

然后注释您的字段以使用它:

@JsonSerialize(nullsUsing = MySerializer.class)
private String university;

通过定义nullsUsing,您可以确保仅为null值调用自定义序列化程序,并且仅针对带注释的字段。

顺便说一句,使用@JsonSerialize(nullsUsing = MySerializer.class)为您的课程添加注释无效 - 请参阅JsonSerialize文档了解详情。