有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使Jackson在反序列化期间无法将double转换为int

我使用Jackson将JSON反序列化为不可变的自定义Java对象。下面是课堂:

final class DataPoint {
  private final int count;
  private final int median;

  @JsonCreator
  DataPoint(
      @JsonProperty("count") int count,
      @JsonProperty("median") int median) {
    if (count <= 0) {
      throw new IllegalArgumentException("...");
    }
    this.count = count;
    this.median = median;
  }

  // getters...
}

以下是我反序列化的JSON:

{
  "count": 1,
  "median": 2
}

它很好用。现在我中断JSON,即用十进制替换整数median

{
  "count": 1,
  "median": 0.1
}

现在我得到count == 1median == 0。相反,我希望Jackson的反序列化失败,因为JSON属性median的数据类型和形式的median参数类型(一个int)是不同的,转换实际上会释放数据

以下是反序列化代码:

String json = "..."; // the second JSON
ObjectMapper mapper = new ObjectMapper()
    .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES)
    .enable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES)
    .enable(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE);
DataPoint data = mapper.readValue(json, DataPoint.class);

伙计们,我能让Jackson在将十进制反序列化为整数时失败吗

非常感谢你们,伙计们


共 (2) 个答案

  1. # 1 楼答案

    您可以为JSON文档定义JSON模式,并在反序列化到Java对象之前运行验证

    如果将median属性定义为integer类型,则将拒绝浮点数

    这种方法还可以解决允许代表integersfloat numbers也被接受的问题,例如2.0。架构需要定义median属性,如下所示:

    {
      ...
      "median": { "type": "number", "multipleOf": 1.0 }
    }
    
  2. # 2 楼答案

    为此,有一个选项ACCEPT_FLOAT_AS_INT。例如:

    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT);
    

    对于"0.1",您将获得:

    Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not coerce a floating-point value ('0.1') into Integer; enable DeserializationFeature.ACCEPT_FLOAT_AS_INT to allow

    您可以查看相关文档here

    请注意,这是从Jackson 2.6开始提供的