使杰克逊在JSON中的重复属性上失败

时间:2017-05-05 11:29:17

标签: java json jackson deserialization

我使用Jackson将JSON反序列化为不可变的自定义Java对象。这是班级:

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

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

  // getters...
}

这是我反序列化的JSON:

{
  "count": 3,
  "lower": 2,
  "median": 3,
  "upper": 4
}

工作正常。现在我打破了JSON,即将lower属性重复:

{
  "count": 4,
  "lower": 2,
  "lower": 3,
  "median": 4,
  "upper": 5
}

现在我得到count == 4lower == 3。相反,我希望Jackson失败deserilizing,因为JSON中存在重复属性(lower)。

以下是反序列化代码:

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

伙计们,在使用重复的属性键对JSON进行desierializing时,是否可以使Jackson失败?

非常感谢,伙计们!

1 个答案:

答案 0 :(得分:4)

如果有重复的属性,您可以启用STRICT_DUPLICATE_DETECTION使解析器抛出Exception,例如:

String s = "{\"count\": 4,\"lower\": 2,\"lower\": 3,\"median\": 4,\"upper\": 5}";
ObjectMapper mapper = new ObjectMapper();
mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
JsonNode readTree = mapper.readTree(s);
System.out.println(readTree.toString());

这将引发以下异常:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Duplicate field 'lower'

Here's文档。