Make Jackson fail to duplicate property in JSON

I am using Jackson

to deserialize JSON for an immutable custom Java object. Here is the class:

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...
}

      

Here is the JSON I deserialize:

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

      

It works great. Now I am parsing the JSON i.e. I spread the property lower

:

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

      

Now I get count == 4

and lower == 3

. Instead, I would like it to Jackson

not perform deserialization as lower

there is a duplicate property in JSON ( ).

Here's the deserializing code:

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);

      

People, can I make it Jackson

crash when deserializing JSON with double property keys?

Thanks a lot guys!

+3


source to share


1 answer


You can include STRICT_DUPLICATE_DETECTION

to force the parser to throw Exception

if there is a duplicate property like:

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());

      

This will result in the following exception:



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

      

Here is the documentation.

+2


source







All Articles