[英]how to accept json array input in jersey Rest Webservice
我正在使用Jersey.Am開發一個休息Web服務,這對於webservices來說是一個新的。 我需要將客戶列表作為輸入傳遞給rest webservice。 在實現它時遇到了問題。
下面是我的客戶對象類
@Component
public class customer {
private String customerId;
private String customerName;
我的終點如下。 addCust是調用webservice時調用的方法
@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"}}
但是球衣無法將json陣列轉換為客戶陣列。 它返回400.日志顯示“c沒有可行的選擇”。 如何將Json數組作為輸入傳遞給webservice並轉換為Array或ArrayList。 任何幫助贊賞。
您的json無效,字段名稱應始終雙引號,並且數組放在[]內,例如:
{"customers":[{"customerId":"1","customerName":"a"},
{"customerId":"2","customerName":"b"}]}
這就是為什么傑克遜不能解散它。 但是這個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){
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.