【问题标题】:Jackson JSON: only consume a single object from streamJackson JSON:仅使用流中的单个对象
【发布时间】:2019-11-20 10:06:55
【问题描述】:

我试图让 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,但没有看到任何适用的内容。

【问题讨论】:

    标签: java json jackson inputstream


    【解决方案1】:

    如果发现任何尾随标记,您可以使用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 或其他任何东西都没有关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-08
      • 1970-01-01
      • 2013-04-24
      • 1970-01-01
      • 2021-03-05
      相关资源
      最近更新 更多