0

I have a POST endpoint which accepts a JSON as request body.

@Path("/drink")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class DrinkResource {

    @POST
    public Drink getDrink(Fruit fruit) {
        return new Drink(fruit.getName());
    }
}

The request body is supposed to be deserialized into this POJO :

public class Fruit {

    private final String name;

    @JsonCreator
    public Fruit(@JsonProperty("name") String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

I'm using Jackson for the deserialization.

Is it possible to make the deserialization fail when the JSON in the request body has duplicate keys ?

For example, if the request body looks like this : {"name" : "banana", "name" : "orange"}, I would like to get a 500 status code or another kind of error instead of having the json deserialized with the last property.

Basically, I'm looking for a solution with the same logic as the JsonParser.Feature.STRICT_DUPLICATE_DETECTION with the ObjectMapper but for a POST endpoint.

I'm also using quarkus so I don't know if there is a property for this. Something similar to quarkus.jackson.fail-on-unknown-properties=true but for the duplicate properties.

TheRelax
  • 35
  • 1
  • 6
  • Since you can't have multiple properties with same name, at least in Java class, hence, you will have to change the second name too, i.e. the orange one, else , I believe the value should be overridden in Java controller. If you would like to send a list, I suggest to make name as ArrayList and pass fruit names comma separated – Harsh Dec 19 '22 at 10:20
  • Alternatively, feel free to check this https://stackoverflow.com/questions/21832701/does-json-syntax-allow-duplicate-keys-in-an-object – Harsh Dec 19 '22 at 10:21

1 Answers1

2

Add the following:

@Singleton
public class MyCustomizer implements ObjectMapperCustomizer {
    @Override
    public void customize(ObjectMapper objectMapper) {
        objectMapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
    }
}

If you do, the ObjectMapper that Quarkus uses will throw a JsonParseException thus leading to a HTTP 400 response.

geoand
  • 60,071
  • 24
  • 172
  • 190