首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Jackson / Springboot解析Optional<T>时出错

使用Jackson / Springboot解析Optional<T>时出错
EN

Stack Overflow用户
提问于 2018-08-31 23:03:40
回答 5查看 732关注 0票数 0

我有一个类,并且更喜欢像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)",

EN

回答 5

Stack Overflow用户

回答已采纳

发布于 2018-09-05 08:08:57

在不改变任何现有代码的情况下,将杰克逊升级到2.8.6版本修复了它。

我确实遵循了上面的另一个答案,奇怪的是,升级到更高版本的‘2.9.6’不起作用。然而,它确实给了我一个新的错误消息,最终将我带到了一个其他人也不得不降级的帖子。

票数 1
EN

Stack Overflow用户

发布于 2018-08-31 23:07:14

您需要将第二个示例更改为

public TestClass(@JsonProperty("testValue") int testValue) {
    this.testValue = Optional.of(testValue);
}
票数 0
EN

Stack Overflow用户

发布于 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://www.baeldung.com/jackson-optional

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52118217

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档