Jackson JSON: 只消耗流中的单个对象

Jackson JSON: only consume a single object from stream

我正在尝试让 Jackson 从输入流中读取单个对象,然后停止读取。看起来默认行为是读取整个流并丢弃任何无关数据,如以下代码示例所示:

    byte[] data = "{\"hello\": 1} abc".getBytes();
    InputStream is = new ByteArrayInputStream(data);
    new ObjectMapper().readTree(is);

    System.out.println(String.format("-> %s", new String(IOUtils.toByteArray(is))));

输出 ->.

有没有办法让 Jackson 只使用来自 InputStream 的数据,直到它读取完整的 JSON 值?或者,如果文件末尾有任何无关数据,则让它失败?

我查看了 JsonParser.Feature,但我没有看到任何适用的内容。

如果找到任何尾随标记,您可以使用 DeserializationFeature.FAIL_ON_TRAILING_TOKENS 生成 JsonParseException。您只需在 ObjectMapper:

中启用它
ObjectMapper mapper = new ObjectMapper()
        .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS);
JsonNode tree = mapper.readTree(input);

这将产生以下异常:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unrecognized token 'abc': was expecting ('true', 'false' or 'null')
 at [Source: (String)"{"value": "test"} abc"; line: 1, column: 43]

顺便说一下,如果您传递 StringInputStream 或其他任何东西都没有关系。