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

标签 java json jackson objectmapper

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

相关文章:

java - 扩展 Jackson 自定义序列化器

java - 改造:用一个元素反序列化数组时出错: "out of START_ARRAY token"

java - JTabbedPane中添加的选项卡不显示

javascript - 在 angularjs 中获取 json 响应对象的最佳实践

php json_encode 部分不适用于数组

javascript - 使用 javascript/jQuery 更改 JSON 数据的图像源

java - 使用 Jackson 将 Java 列表序列化为 XML 和 JSON

java - 我可以使用 Maven war 作为覆盖已经存在的其他项目的一种形式吗?

java - 如何获取 GMT 格式的时区表示

java - ChannelInboundHandlerAdapter writeAndFlush(msg)方法在刷新后是否释放msg?