Search code examples
javajsonweb-servicesrestjersey

How correctly produce JSON by RESTful web service?


I am writing a web service the first time. I created a RESTful web service based on Jersey. And I want to produce JSON. What do I need to do to generate the correct JSON type of my web service?

Here's one of my methods:

@GET
@Path("/friends")
@Produces("application/json")
public String getFriends() {
    return "{'friends': ['Michael', 'Tom', 'Daniel', 'John', 'Nick']}";
}

Is it sufficient that I simply point out annotation @Produces("application/json") for my method? Then this method may return any type of object? Or only String? Do I need additional processing or transformation of these objects?

Please help me as a beginner to deal with these issues. Thanks in advance!


Solution

  • You can annotate your bean with jaxb annotations.

      @XmlRootElement
      public class MyJaxbBean {
        public String name;
        public int age;
    
        public MyJaxbBean() {} // JAXB needs this
    
        public MyJaxbBean(String name, int age) {
          this.name = name;
          this.age = age;
        }
      }
    

    and then your method would look like this:

       @GET @Produces("application/json")
       public MyJaxbBean getMyBean() {
          return new MyJaxbBean("Agamemnon", 32);
       }
    

    There is a chapter in the latest documentation that deals with this:

    https://jersey.java.net/documentation/latest/user-guide.html#json