ObjectMapper.readTree在无效输入上不会引发IOException

时间:2019-11-07 16:01:40

标签: java jackson jackson-databind

我正在使用Jackson数据绑定2.9.10。根据文档说明:

  

如果发生解析问题(无效的JSON),则会引发JsonParseException

请参阅:ObjectMapper.readTree

我进行了以下测试:

    // Given
    String invalidJson = new POJONode("}{").toString();
    final InputStream mockInputStream = new ByteArrayInputStream(invalidJson.getBytes());

    // When
    myLambda.handleRequest(mockInputStream, mockOutputStream, mockContext);

    // Then
    Expect some stuff to happen in the catch JsonProcessingException bit

但是,readTree将其转换为TextNode并且不会引发异常...

调试: enter image description here

如何配置ObjectMapper抛出无效输入?

1 个答案:

答案 0 :(得分:0)

在打印invalidJson变量时,您会看到"}{",它实际上是有效的JSON,对应于json.org。您也可以使用jsonformatter之类的网络工具来确认。当您直接将invalidJson变量设置为此字符串时,解析器将引发异常:

String invalidJson = "}{";

您应该看到:

Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Unexpected close marker '}': expected ']' (for root starting at [Source: (String)"}{"; line: 1, column: 0])
 at [Source: (String)"}{"; line: 1, column: 2]