代码之家  ›  专栏  ›  技术社区  ›  Michael Puckett II

用Jackson/Springboot解析可选<T>时出错

  •  0
  • Michael Puckett II  · 技术社区  · 7 年前

    我有一个班级,希望有价值观 Optional<T> 例如 Optional<Integer> value; .

    Springboot json .

    java 可选<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' 
    

    int Optional<Integer> 我从web调用中得到以下错误响应。

    “例外”: "org.springframework.http.converter.HttpMessageToradableException异常", “message”:“JSON解析错误:0;嵌套异常为” (我的类路径)[“操作\”]->java.util.ArrayList[3])",

    5 回复  |  直到 7 年前
        1
  •  1
  •   Michael Puckett II    7 年前

    无需更改任何现有代码即可升级到版本 2.8.6 修好了。

        2
  •  0
  •   muzychuk    7 年前

    你需要把第二个例子改成

    public TestClass(@JsonProperty("testValue") int testValue) {
        this.testValue = Optional.of(testValue);
    }
    
        3
  •  0
  •   Mike    7 年前

    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

        4
  •  0
  •   Artem Karp    7 年前

        5
  •  0
  •   ksadjad    7 年前

    可选意味着它不一定有你要找的对象!所以你可以简单地使用包装器。您可以返回对象(如果对象存在),也可以返回404状态(如果对象不存在)。

    public static <X> ResponseEntity<X> wrapOrNotFound(Optional<X> maybeResponse, HttpHeaders header) {
        return maybeResponse.map(response -> ResponseEntity.ok().headers(header).body(response))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }