如何通过RESTful Web服务正确生成JSON?
我是第一次写网络服务。 我创建了一个基于Jersey的RESTful Web服务。 我想制作JSON 。 如何生成正确的JSON类型的Web服务需要做什么?
这是我的一个方法:
@GET @Path("/friends") @Produces("application/json") public String getFriends() { return "{'friends': ['Michael', 'Tom', 'Daniel', 'John', 'Nick']}"; }
我只是为我的方法指出@Produces("application/json")
注释就足够了吗? 那么这个方法可能会返回任何类型的对象? 还是只有String? 我是否需要对这些对象进行额外处理或转换?
请帮助我作为初学者来处理这些问题。 提前致谢!
您可以使用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; } }
然后你的方法看起来像这样:
@GET @Produces("application/json") public MyJaxbBean getMyBean() { return new MyJaxbBean("Agamemnon", 32); }
最新文档中有一章涉及此问题:
https://jersey.java.net/documentation/latest/user-guide.html#json
您可以使用像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" ]}
编辑这样做的好处是,您可以在不同的层中构建响应并将它们作为对象返回
@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']}"; }
@POST @Path ("Employee") @Consumes("application/json") @Produces("application/json") public JSONObject postEmployee(JSONObject jsonObject)throws Exception{ return jsonObject; }
使用此注释
@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})