我正在使用 Jersey 开发一个休息网络服务。我对网络服务有点陌生。我需要将客户列表作为输入传递给 rest webservice。在实现它时遇到问题。
下面是我的客户对象类
@Component
public class customer {
private String customerId;
private String customerName;
我的端点如下。 addCust 是将在调用 web 服务时调用的方法
@Path("/add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String addCust(@Valid customer[] customers){
//And json input is as below
{customers:{"customerId":"1","customerName":"a"},
{"customerId":"2","customerName":"b"}}
但是 Jersey 无法将 json 数组转换为客户数组。它正在返回 400。并且日志显示“在 c 处没有可行的替代方案”。如何将 Json 数组作为输入传递给 webservice 并转换为 Array 或 ArrayList。任何帮助表示赞赏。
最佳答案
您的 json 无效,字段名称应始终用双引号引起来,并且数组放在 [] 内例如:
{"customers":[{"customerId":"1","customerName":"a"},
{"customerId":"2","customerName":"b"}]}
这就是 jackson 无法解码它的原因。但是这个 json 永远不会适合你的 api。 以下是您应该发送的内容的示例:
[{"customerId":"1","customerName":"a"},{"customerId":"2","customerName":"b"}]
另一件事是您可以使用集合而不是数组:
@Path("/add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String addCust(@Valid List<Customer> customers){
如果你想发送这样的 json:
{"customers":[{"customerId":"1","customerName":"a"},
{"customerId":"2","customerName":"b"}]}
然后你必须用“customers”属性将所有东西包装到类中:
class AddCustomersRequest {
private List<Customer> customers;
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
public void getCustomers() {
return this.customers;
}
}
并在您的 API 中使用它:
@Path("/add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String addCust(@Valid AddCustomersRequest customersReq){
关于java - 如何在 jersey Rest Webservice 中接受 json 数组输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32510240/