Search code examples
javajsonjacksonobjectmapper

ObjectMapper doesn't fail on trailing characters


I'm having the following class:

public class Car{
private String id;
private String name;

public Car() {
}

public Car(String id, String name) {
    this.id = id;
    this.name = name;
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

and I use it like this:

String json = "{\"id\":\"1\", \"name\":\"hh\"} {\"id\":\"2\", \"name\":\"ccc\"}";

    Car car;
    try {
        ObjectMapper mapper = new ObjectMapper();
        car = mapper.readValue(json, new TypeReference<Car>() {
        });
    } catch (IOException e) {
        car = null;
    }

I'm expecting it to fail but instead, I get the first object in the input, the "first" car object.

why is that happening?


Solution

  • You need to enable FAIL_ON_TRAILING_TOKENS feature to throw an exception in this case:

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
    

    or since version 2.10:

    ObjectMapper mapper = JsonMapper.builder()
            .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
            .build();
    

    From documentation:

    Feature that determines behaviour for data-binding after binding the root value. If feature is enabled, one more call to JsonParser.nextToken() is made to ensure that no more tokens are found (and if any is found, MismatchedInputException is thrown); if disabled, no further checks are made. Feature could alternatively be called READ_FULL_STREAM, since it effectively verifies that input stream contains only as much data as is needed for binding the full value, and nothing more (except for possible ignorable white space or comments, if supported by data format).

    Feature is disabled by default (so that no check is made for possible trailing token(s)) for backwards compatibility reasons.

    You can enable all features from FAIL_ON_* family to be as strict as possible.