如何在泽西Rest Webservice中接受json数组输入
Am developing a rest webservice using Jersey.Am slightly new to webservices. I need to pass List of customer as input to rest webservice. having issue in achieving it.
我正在使用Jersey.Am开发一个休息网络服务,这对于webservices来说是一个新的东西。我需要将客户列表作为输入传递给rest webservice。在实现它时遇到了问题。
Below is my customer object class
以下是我的客户对象类
@Component
public class customer {
private String customerId;
private String customerName;
And my endpoint is as below. addCust is the method that will be called on calling the webservice
我的终点如下。 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"}}
But jersey is not able to convert json array to Array of Customers. It is returning 400. And the logs shows "no viable alternative at c". How to pass Json array as input to webservice and convert into Array or ArrayList. Any help appreciated.
但是球衣无法将json阵列转换为客户阵列。它返回400.日志显示“c没有可行的选择”。如何将Json数组作为输入传递给webservice并转换为Array或ArrayList。任何帮助赞赏。
1 个解决方案
#1
4
Your json is invalid, field names should be always double quotted, and arrays are placed inside [] for example:
您的json无效,字段名称应始终双引号,并且数组放在[]内,例如:
{"customers":[{"customerId":"1","customerName":"a"},
{"customerId":"2","customerName":"b"}]}
thats why jackson cannot unmarshall it. But this json will never fit your api. Here is an example of what You should send:
这就是为什么杰克逊不能解散它。但这个json永远不适合你的api。以下是您应该发送的示例:
[{"customerId":"1","customerName":"a"},{"customerId":"2","customerName":"b"}]
Another thing is that You can use collections instead of arrays:
另一件事是您可以使用集合而不是数组:
@Path("/add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String addCust(@Valid List<Customer> customers){
If you want to send a json like this:
如果你想发送一个像这样的json:
{"customers":[{"customerId":"1","customerName":"a"},
{"customerId":"2","customerName":"b"}]}
then you have to wrap everything into class with "customers" property:
那么你必须用“客户”属性将所有内容包装到类中:
class AddCustomersRequest {
private List<Customer> customers;
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
public void getCustomers() {
return this.customers;
}
}
And use it in Your API:
并在您的API中使用它:
@Path("/add")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public String addCust(@Valid AddCustomersRequest customersReq){
更多相关文章
- java数组的拷贝四种方法:for、clone、System.arraycopy、arrays.c
- 给定一个整数数组,找出两个下标,要求后面下标所指的数减去前面下标
- Java中怎么把字符串数组转为整形数组
- 剑指Offer(六)旋转数组的最小数字(Java版 )
- Java中double型数组的HashCode产生
- JavaWeb-1-IOS或Android客户端上传图片到Java服务端存到数据库,再
- Netty学习心得 netty服务端和客户端的连接
- socket实现客户端与服务端通信(一)服务端
- 求助:json + java 返回 数据 数组中去掉双引号