无法在REST WS中反序列化LocalDate值

时间:2019-02-13 08:28:58

标签: java rest spring-boot jackson postman

我正在使用一个非常简单的{'_control_qubits': [], '_engine': <__main__.MainEngine object at 0x7fc323e4d198>, '_qubits': ([<projectq.types._qubit.WeakQubitRef object at 0x7fc30b0b1080>],), 'gate': <projectq.ops._gates.XGate object at 0x7fc316778048>, 'tags': []} REST WSSpringBoot来发送,接收和显示数据。问题是,PostMan值反序列化似乎存在问题,由于某种原因,它仅接受此格式Date(用破折号分隔)。

例如,如果我从yyyy-mm-dd发送以下数据,则我收到的响应没有问题:

Postman

但是,如果我执行以下操作(起息日期不带破折号):

{  
   "server":{  
      "address":"url",
      "port":2555525
   },
   "date":"2019-02-13"
}

我收到以下错误:

{  
   "server":{  
      "address":"url",
      "port":2555525
   },
   "date":"20190213"
}

我想要实现的是能够对日期进行反序列化,而不考虑{ "timestamp": 1550046097893, "status": 400, "error": "Bad Request", "message": "JSON parse error: Cannot deserialize value of type `java.time.LocalDate` from String \"20190213\": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '20190213' could not be parsed at index 0; nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.time.LocalDate` from String \"20190213\": Failed to deserialize java.time.LocalDate: (java.time.format.DateTimeParseException) Text '20190213' could not be parsed at index 0\n at [Source: (PushbackInputStream); line: 6, column: 9] (through reference chain: com.restws.webservices.model.Admin[\"date\"])", "path": "/v3/admin/device" } 中输入的格式。有办法吗?

这是我的控制器:

PostMan

还有POJO:

@Controller
@RequestMapping("/v3/admin/")
public class AdminController {

    Logger logger = LoggerFactory.getLogger(AdminController.class);

    @Autowired
    private ObjectMapper objectMapper;

    @RequestMapping(method = RequestMethod.POST, value = "/device", consumes ="application/json")
    public ResponseEntity putDevice(@RequestBody Admin admin) throws IOException {

        logger.info(admin.toString());
        String adminString = admin.toString();
        return new ResponseEntity<>(adminString, HttpStatus.OK);

    }
}

//

@JsonIgnoreProperties(ignoreUnknown = true)
public class Admin {

    @JsonProperty("server")
    private Server server;

    @JsonProperty("date")
    private LocalDate date;

    public Admin() {
    }


    public Server getServer() {
        return server;
    }

    public void setServer(Server server) {
        this.server = server;
    }

    public LocalDate getDate() {
        return date;
    }

    public void setDate(LocalDate date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).append("server", server).append("date", date).toString();
    }
}

1 个答案:

答案 0 :(得分:1)

您可以尝试编写自定义JsonDeserializer来以您要接受的格式处理日期反序列化: JSON serialization strategy for dates