java - Spring中Json无法反序列化实例错误

标签 java json spring http

我正在尝试发送一个 json 长列表并从数据库中获取记录。

我的 Controller 是:

@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 在 postman 中测试了这项服务:

{ "ids": [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()

关于java - Spring中Json无法反序列化实例错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52666929/

相关文章:

java - 未通过身份验证时显示登录对话框

java - 使用 mvn liquibase :diff? 时如何禁用删除表和列

Java Jackson JSON 解析为 Map<String, String>

java - 如何使用Optional调用类方法

json - Messenger 目标广告的无效页面欢迎消息 - Facebook

python - 使用 Python 提取 JSON 文件中的嵌套项

java - 使用 Hibernate 和 Spring 的 Swing 应用程序

java - Hazelcast - 关闭最后一个节点时保留数据

java - Java 中的正则表达式点运算符似乎总是贪婪地工作

java - 在字符串中查找 URL