杰克逊强迫归零

时间:2015-11-05 15:38:39

标签: java json jackson jax-rs

使用JAX-RS(GlassFish 4)和Jackson作为序列化程序,我在类型Double的POJO属性的反序列化过程中遇到了问题(与Integer相同)。

让我们说我有简单的POJO(不包括其他成员,吸气剂和制定者):

public class MapConstraints {    

    private Double zoomLatitude;

    private Double zoomLongitude;   
}

当用户以{ "zoomLatitude": "14.45", "zoomLongitude": ""}格式向API发送请求时,zoomLatitude的值设置为14.45,但zoomLongitude的值设置为0

如果没有显示任何值,我预计zoomLongitude的值为null。我尝试使用ObjectMapper配置JsonInclude.Include.NON_EMPTY,但没有成功。

与genson相同的结果。

2 个答案:

答案 0 :(得分:2)

您可以使用@JsonInclude注释您的POJO,以指明将(de)序列化的值:

@JsonInclude(Include.NON_EMPTY)
private Double zoomLongitude

在Jackson 2.6中,可以使用以下values

但是,如果@JsonInclude values不符合您的需求,您可以创建自定义JsonDeserializer

public class CustomDeserializer extends JsonDeserializer<Double> {

    @Override
    public Double deserialize(JsonParser jp, DeserializationContext ctxt) 
      throws IOException, JsonProcessingException {

        String text = jp.getText();
        if (text == null || text.isEmpty()) {
            return null;
        } else {
            return Double.valueOf(text);
        }
    }
}

然后使用@JsonDeserialize注释您的字段,指明您要使用的反序列化程序:

public class MapConstraints {

    @JsonDeserialize(using = CustomDeserializer.class)
    private Double zoomLatitude;

    @JsonDeserialize(using = CustomDeserializer.class)
    private Double zoomLongitude;
}

答案 1 :(得分:0)

在POJO上使用此注释:

@JsonInclude(Include.ALWAYS)