gpt4 book ai didi

java - ObjectMapper 不会在尾随字符上失败

转载 作者:行者123 更新时间:2023-12-04 09:57:44 27 4
gpt4 key购买 nike

我有以下类(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 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.



您可以启用来自 FAIL_ON_* 的所有功能家庭尽可能严格。

关于java - ObjectMapper 不会在尾随字符上失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61887954/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com