如何在Spring Boot中反序列化数组对象

时间:2018-08-26 20:31:04

标签: java json spring spring-boot

我的问题很简单,我有一个spring boot控制器,它可以记录如下对象:

@RequestMapping(value = "/contracts/{id}/milestones", method = RequestMethod.PUT, headers = "Accept=application/json")
    @ResponseBody
    @Transactional
    public ResponseEntity<?> updateContractMilestones(@PathVariable("id") String contractId,
            @DTO(MilestoneUpdateStateDto.class) List<Milestone> milestones,UriComponentsBuilder uriComponentsBuilder, final HttpServletRequest request) {
}

但是当我发送以下Json对象时:

[{"id":18,"state":"FINALIZED"},{"id":19,"state":"FINALIZED"}]

我收到以下错误:

  

无法读取HTTP消息:   org.springframework.http.converter.HttpMessageNotReadableException:   JSON解析错误:无法反序列化的实例   com.espiritware.opusclick.dto.MilestoneUpdateStateDto出   START_ARRAY令牌;嵌套异常为   com.fasterxml.jackson.databind.exc.MismatchedInputException:无法   反序列化的实例   com.espiritware.opusclick.dto.MilestoneUpdateStateDto出   START_ARRAY令牌

我的问题是,我应该从后端做些什么才能能够无错误地接收此对象?

非常感谢!

1 个答案:

答案 0 :(得分:0)

将您的方法签名更新为

@RequestMapping(value = "/contracts/{id}/milestones", method = RequestMethod.PUT, headers = "Accept=application/json")
@ResponseBody
@Transactional
public ResponseEntity<?> updateContractMilestones(
    @PathVariable("id") String contractId, 
    List<MilestoneUpdateStateDto> milestones,
    ...
)

并尝试使用此JSON

{
 [
  {"id":18, "state":"FINALIZED"},
  {"id":19, "state":"FINALIZED"}
 ]
}