如何通过RESTful Web服务正确生成JSON?

Phi*_*uno 19 java rest json web-services jersey

我是第一次写网络服务.我创建了一个基于Jersey的RESTful Web服务.我想制作JSON.如何生成正确的JSON类型的Web服务需要做什么?

这是我的一个方法:

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

我只是@Produces("application/json")为我的方法指出注释就足够了吗?那么这个方法可能会返回任何类型的对象?还是只有String?我是否需要对这些对象进行额外处理或转换?

请帮助我作为初学者来处理这些问题.提前致谢!

pla*_*147 31

您可以使用jaxb注释来注释bean.

  @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;
    }
  }
Run Code Online (Sandbox Code Playgroud)

然后你的方法看起来像这样:

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

最新文档中有一章涉及此问题:

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


The*_*Man 5

您可以使用像org.json这样的包http://www.json.org/java/

因为您需要更频繁地使用JSONObjects.

在那里,您可以轻松创建JSONObjects并在其中放入一些值:

 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"
    ]}
Run Code Online (Sandbox Code Playgroud)

编辑这样做的好处是,您可以在不同的层中构建响应并将它们作为对象返回