Spring Boot杰克逊java.time.Duration

adh*_*ock 3 java spring java-8

我已经创建了一个宁静的Web服务,并且尝试发送上述课程的发帖请求

public class A {
    Duration availTime;
}

public class MyRest {
    @RequestMapping(value = "/test", method = RequestMethod.POST)
    public Response<?> test(@RequestBody A ta) {
        return new ResponseEntity<>(HttpStatus.OK);`
    }
}
Run Code Online (Sandbox Code Playgroud)

原始请求主体

{
  "availTime": {
    "seconds": 5400,
    "nano": 0,
    "units": [
      "SECONDS",
      "NANOS"
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

预期的json结果

 {"availTime": "PT1H30M"}
Run Code Online (Sandbox Code Playgroud)

我收到了以上错误:无法读取HTTP消息:

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Unexpected token (START_OBJECT),
expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Duration value; nested exception is
com.fasterxml.jackson.databind.exc.MismatchedInputException: Unexpected token (START_OBJECT), expected one of [VALUE_STRING, VALUE_NUMBER_INT, VALUE_NUMBER_FLOAT] for java.time.Duration value
Run Code Online (Sandbox Code Playgroud)

Pra*_*tel 7

作为例外,java.time.Duration只能从或创建int,但您要提供Json对象。floatstring

将您的Duration类定义为

public class Duration {

    private long seconds;
    private long nano;
    private List<String> units;

    // setters / getters
}
Run Code Online (Sandbox Code Playgroud)

现在您的请求将根据课程进行映射 A

编辑1
如果仍然要映射到java.time.Duration,则需要更改请求正文。
案例1(int)

  • 请求正文

    {“ availTime”:5400}

  • 输出量

    {“ availTime”:“ PT1H30M”}

案例2(浮动)

  • 请求正文

    {“ availTime”:5400.00}

  • 输出量

    {“ availTime”:“ PT1H30M”}

情况3(字串)

  • 请求正文

    {“ availTime”:“ PT5400S”}

  • 输出量

    {“ availTime”:“ PT1H30M”}

对于上述所有三种情况,添加依赖项

<dependency>
  <groupId>com.fasterxml.jackson.datatype</groupId>
  <artifactId>jackson-datatype-jsr310</artifactId>
  <version>2.8.8</version>
</dependency>
Run Code Online (Sandbox Code Playgroud)

A类应修改为

public class A {

    private Duration availTime;

    // for json output of duration as string 
    @JsonFormat(shape = Shape.STRING)
    public Duration getAvailTime() {
        return availTime;
    }

    public void setAvailTime(Duration availTime) {
        this.availTime = availTime;
    }
}
Run Code Online (Sandbox Code Playgroud)

将请求正文打印为json

ObjectMapper mapper = new ObjectMapper();
mapper.findAndRegisterModules();
System.out.println(mapper.writeValueAsString(ta));
Run Code Online (Sandbox Code Playgroud)

如果仍然要映射现有的请求主体,则需要为Duration类编写自定义反序列化器。

希望能帮助到你。

  • 是的,但是只能使用int,float或string创建。参见https://github.com/FasterXML/jackson-datatype-jsr310/blob/master/src/main/java/com/fasterxml/jackson/datatype/jsr310/deser/DurationDeserializer.java#L48 (2认同)