使用@RequestBody接收List<T>时遭遇Jackson反序列化错误求助
解决Spring Boot接收List类型请求体的反序列化错误
错误原因
你的接口方法声明接收List<EstatePropertyCreatorDto>类型的请求体,意味着Jackson期望直接解析JSON数组,但你实际发送的是一个包含estateProperties数组的JSON对象,类型不匹配导致反序列化失败。
解决方案(二选一)
方案1:修改请求体为直接数组格式
把请求体外层的对象包裹去掉,直接传数组:
[ { "id": "8bd050b0-6578-443a-8e22-bf48318734ce", "title": "test title", "type": "APARTMENT", "floor": "5", "details": "This details should be aware of!" }, { "id": "69786c5f-e35a-476d-82de-1d5833a12818", "title": "test title for 2nd", "type": "GARAGE", "alias": "jamie garage", "floor": "1", "details": "Details for Jamie Garage" }, { "id": "c935f330-eebe-4d35-818d-d2248fc8ca9e", "title": "test title for 3rd", "type": "OFFICE", "floor": "2", "details": "Details for Jamie office", "commonParts": "Office common parts" } ]
方案2:后端创建包装类适配现有请求格式
如果前端无法修改请求体结构,就创建一个包装DTO来接收整个对象:
@Getter @Setter @NoArgsConstructor public class EstatePropertyListDto { private List<EstatePropertyCreatorDto> estateProperties; }
然后修改控制器方法的参数类型:
@PostMapping("/{buildingId}/properties") public List<EstatePropertyCreatorDto> addPropertiesToBuilding(@PathVariable UUID buildingId, @RequestBody EstatePropertyListDto propertyList) { buildingService.addPropertiesToBuilding(buildingId, propertyList.getEstateProperties()); // 后续实现返回逻辑 return List.of(); }
内容的提问来源于stack exchange,提问作者martoiliev
相关产品推荐
相关产品推荐

