java - Json无法反序列化Spring中的实例错误
问题描述
我正在尝试发送一个 json 长列表并从数据库中获取记录。
我的控制器是:
@Api(tags = Endpoint.RESOURCE_customer, description = "customer Resource")
@RestController
@RequestMapping(produces = MediaType.APPLICATION_JSON_VALUE,consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.OK)
public class CustomerResourceController {
private final customerService customerService;
public CustomerResourceController(customerService customerService) {
this.customerService = customerService;
}
@ApiOperation(
value = "Return customer",
response = customerDto.class, responseContainer="List"
)
@PostMapping(value = Endpoint.RRESOURCE_customer_ID)
public List<customerDto> getCustomersByIds(@RequestBody List<Long> ids) {
return customerService.findcustomerIds(ids);
}
}
客户端类是:
@Headers("Content-Type: " + MediaType.APPLICATION_JSON_VALUE)
public interface CustomerClient {
@RequestLine("POST /customer/customers/search")
List<LocGrpDto> getCustomersByIds(@RequestBody @Validated List<Long> ids);
}
我用 JSON 在邮递员中测试了这个服务:
{“ID”:[1,7,8] }
但我得到这个错误:
{
"timestamp": "2018-10-05T13:29:57.645+0000",
"status": 400,
"error": "Bad Request",
"message": "Could not read document: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@3cb8b584; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@3cb8b584; line: 1, column: 1]",
"path": "/api/v1/customer/customers/search",
"errors": []
}
问题是什么?您是否在这里看到任何问题,或者可能是由于我的服务类或 dto 类引起的?
解决方案
尝试使用有效负载请求[1,7,8]
,而不是{"ids": [1,7,8]}
.
您的 JSON 将转换为具有下一种格式的请求正文。
class Body {
private List<Long> ids;
// constructor, getters and setters
}
对于 REST 客户端,您可以查看RestTemplate
.
RestTemplate template;
List<Long> ids;
List<CustomerDto> = template.exchange(
"/customer/customers/search",
HttpMethod.POST,
new HttpEntity<>(ids),
new ParameterizedTypeReference<List<CustomerDto>>() {}).getBody()
推荐阅读
- nginx - 使用 nginx 重定向到 S3 时避免使用 CORS
- cassandra - 我们可以使用“NullCompactionStrategy”吗?
- curl - Post Request 适用于 Postman,但不适用于 cURL
- sharepoint - Sharepoint 2019:应用目录网站的问题
- google-maps - 是否可以使用谷歌地方 API 获得一个国家的主要细分级别?
- php - 无法在 codeigniter 中保留 post 变量
- angular - 角材料 MatProgressButton 禁用属性不起作用?
- android - 如何使用谷歌相机(GCAM)在android中实现基于相机的应用程序?
- c++ - 使用 -g 标志使用 makefile 编译单个 c++ 文件不起作用
- android - Android:集群标记计数未使用自定义标记正确显示