我有一个类(class),并且希望拥有值 Optional<T>
如Optional<Integer> value;
.
在此项目中Springboot
用于创建 Web Controller ,客户端通过 json
发送/接收.
当客户端put或post时,解析类在java
有Optional<T>
输入参数,失败;否则它工作正常。然而; Optional<T>
是首选,因为我们希望让客户端能够省略不使用的字段。
例如:
这有效:
public class TestClass {
private final int testValue;
public TestClass(@JsonProperty("testValue") int testValue) {
this.testValue = testValue;
}
public int getTestValue() {
return testValue;
}
}
这不会:
public class TestClass {
private final Optional<Integer> testValue;
public TestClass(@JsonProperty("testValue") Optional<Integer> testValue) {
this.testValue = testValue;
}
public Optional<Integer> getTestValue() {
return testValue;
}
}
以下是 Gradle 的一些版本行。
springBootVersion = '1.5.8.RELEASE'
<小时/>
compile group: 'com.fasterxml.jackson.dataformat', name: 'jackson-dataformat-xml', version: '2.6.4'
compile group: 'com.fasterxml.jackson.datatype', name: 'jackson-datatype-jdk8', version: '2.6.3'
使用 Postman 进行 POST 时,值为 int
事情有效。当我使用Optional<Integer>
时我从网络调用中收到以下错误响应。
总结:
"exception": "org.springframework.http.converter.HttpMessageNotReadableException", "message": "JSON parse error: 0; nested exception is com.fasterxml.jackson.databind.JsonMappingException: 0 (through reference chain: …(my class path)… [\"actions\"]->java.util.ArrayList[3])",
最佳答案
在不更改任何现有代码的情况下,将 Jackson 升级到版本 2.8.6
修复了该问题。
我确实遵循了上面的另一个答案,奇怪的是,升级到更高版本的“2.9.6”不起作用。然而,它确实给了我一条新的错误消息,最终导致我发现其他人也必须降级的线程。
关于java - 使用 Jackson/Springboot 解析可选 <T> 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52118217/