我正在使用 Jackson 数据绑定(bind) 2.9.10
。根据它声明的文档:
If a parsing problem occurs (invalid JSON), JsonParseException will be thrown
我有以下测试:
// 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
并且不会抛出异常...
如何配置 ObjectMapper 以抛出无效输入?
最佳答案
当您打印 invalidJson
变量时,您将看到 "}{"
根据 json.org 这实际上是一个有效的 JSON
.您还可以确认使用一些网络工具,如 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]
关于java - ObjectMapper.readTree 不会在无效输入时抛出 IOException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58752623/