我正在使用Jersey.Am开发一个休息的Web服务。我需要将客户列表作为输入传递给其余的Web服务。在实现它时遇到问题。
下面是我的客户对象类
@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数组转换为Customer Array。现在返回400。日志显示“在c处没有可行的选择”。如何将Json数组作为输入传递到Web服务并转换为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"}]}
那么您必须使用“客户”属性将所有内容包装到类中:
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){