我有以下类(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;
}
}
我像这样使用它:
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;
}
我期待它失败,但相反,我得到了输入中的第一个对象,即“第一个”汽车对象。
为什么会这样?
最佳答案
您需要启用 FAIL_ON_TRAILING_TOKENS在这种情况下抛出异常的功能:
ObjectMapper mapper = new ObjectMapper();
mapper.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
或自版本
2.10
:ObjectMapper mapper = JsonMapper.builder()
.enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS)
.build();
从文档:
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 calledREAD_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.
您可以启用来自
FAIL_ON_*
的所有功能家庭尽可能严格。
关于java - ObjectMapper 不会在尾随字符上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61887954/