杰克逊强制归零

Jackson coercing to zero

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

假设我有简单的 POJO(不包括一堆其他字段、getter 和 setter):

public class MapConstraints {    

    private Double zoomLatitude;

    private Double zoomLongitude;   
}

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

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

与 genson 的结果相同。

您可以使用 @JsonInclude 注释您的 POJO 以指示哪些值将被(反)序列化:

@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;
}

在 POJO 上使用此注解:

@JsonInclude(Include.ALWAYS)