Java + Jersey list of entities in input of webservice

廉价感情. 提交于 2019-12-11 19:02:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!