How correctly produce JSON by RESTful web service?

后端 未结 5 1171
无人共我
无人共我 2020-12-08 15:48

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

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-08 16:12

    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

提交回复
热议问题