How correctly produce JSON by RESTful web service?

后端 未结 5 1059
无人共我
无人共我 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

    0 讨论(0)
  • 2020-12-08 16:13
    @POST
    @Path ("Employee")
    @Consumes("application/json")
    @Produces("application/json")
    public JSONObject postEmployee(JSONObject jsonObject)throws Exception{
        return jsonObject;
    }       
    
    0 讨论(0)
  • 2020-12-08 16:23

    You could use a package like org.json http://www.json.org/java/

    Because you will need to use JSONObjects more often.

    There you can easily create JSONObjects and put some values in it:

     JSONObject json = new JSONObject();
     JSONArray array=new JSONArray();
        array.put("1");
        array.put("2");
        json.put("friends", array);
    
        System.out.println(json.toString(2));
    
    
        {"friends": [
          "1",
          "2"
        ]}
    

    edit This has the advantage that you can build your responses in different layers and return them as an object

    0 讨论(0)
  • 2020-12-08 16:25
    @GET
    @Path("/friends")
    @Produces(MediaType.APPLICATION_JSON)
    public String getFriends() {
    
        // here you can return any bean also it will automatically convert into json 
        return "{'friends': ['Michael', 'Tom', 'Daniel', 'John', 'Nick']}";
    }
    
    0 讨论(0)
  • 2020-12-08 16:28

    Use this annotation

    @RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})
    
    0 讨论(0)
提交回复
热议问题