我有一个类,并且更喜欢像Optional<Integer> value;
这样的值为Optional<T>
。
在这个项目中,Springboot
用于创建web控制器,客户端通过json
发送/接收。
当客户端puts或posts,并且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;
}
}
This This:
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'
当POSTing和Postman的值是一个int
时,事情就会发生。当我使用Optional<Integer>
时,我从web调用中得到以下错误响应。
摘要:
JSON " exception ":"org.springframework.http.converter.HttpMessageNotReadableException","message":"JSON解析错误: 0;嵌套异常为com.fasterxml.jackson.databind.JsonMappingException: 0(通过引用链:…(我的类路径)…\"actions\"->java.util.ArrayList3)",
发布于 2018-09-05 08:08:57
在不改变任何现有代码的情况下,将杰克逊升级到2.8.6
版本修复了它。
我确实遵循了上面的另一个答案,奇怪的是,升级到更高版本的‘2.9.6’不起作用。然而,它确实给了我一个新的错误消息,最终将我带到了一个其他人也不得不降级的帖子。
发布于 2018-08-31 23:07:14
您需要将第二个示例更改为
public TestClass(@JsonProperty("testValue") int testValue) {
this.testValue = Optional.of(testValue);
}
发布于 2018-09-01 00:38:30
有一个Jackson模块可以帮助序列化/反序列化Optional
参数。
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jdk8</artifactId>
<version>2.9.6</version>
</dependency>
然后在ObjectMapper
中注册该模块
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new Jdk8Module());
https://stackoverflow.com/questions/52118217
复制相似问题