问题
I need to receive a list of JSON entity as input to my WS.
Here my entity definition:
@XmlRootElement
public class ContactClass {
public String action;
public Long userId;
public String phone;
public String fbId;
}
here my WS function definition:
@PUT
@Path("/{userId}/adBook")
public String synchAdBookContacts(@PathParam("userId") Long userId, ArrayList<ContactClass> contacts)
Removing ArrayList<> It works fine, but I need an array of ContactClass as input.
Can you help me please?
Thank you!
Update: Finally I found the solution, here the article that have solved my issue: https://blogs.oracle.com/japod/entry/missing_brackets_at_json_one
回答1:
Bean 1:
@XmlRootElement
public class Contact {
private String name;
private String phoneNumber;
// Getters, setters, default constructor
}
Bean 2:
@XmlRootElement
public class Contacts {
private List<Contact> contacts;
//Getter for contacts
@XMLElement(name = "listContacts")
public List<Contact> getContacts() {
....
// Getters, setters, default constructor
}
You Json fiel should have the following format:
"listContacts":[{"json for contact1"},{"json for contact2"},{"json for contact3"}...]
Your Resource:
@PUT
@Path("/{userId}/adBook")
public String synchAdBookContacts(@PathParam("userId") Long userId, Contacts contacts) {
//Here you can get your contacts contacts.
回答2:
Deserializing to a list should work just fine. The following code works with RESTeasy + Jackson:
Bean:
@XmlRootElement
public class Contact implements Serializable {
private static final long serialVersionUID = 2075967128376374506L;
private String name;
private String phoneNumber;
// Getters, setters, default constructor
}
Resource:
@Path("/othertest")
public class AnotherTestResource {
@POST
@Path("/list/{id}")
@Produces("application/json")
@Consumes("application/json")
public Response requestWithList(@PathParam("id") String id,
List<Contact> contacts) {
return Response.ok("Hello World: " + contacts.size()).build();
}
}
回答3:
Annotating your synchAdBookContacts method with @Consumes("application/json") should do it. Which JAX-RS implementation are you using and what error are you exactly getting?
来源:https://stackoverflow.com/questions/9550177/java-jersey-list-of-entities-in-input-of-webservice