[英]How correctly produce JSON by RESTful web service?
我是第一次編寫 Web 服務。 我創建了一個基於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")
注釋就足夠了嗎? 那么這個方法可以返回任何類型的對象嗎? 還是只有字符串? 我是否需要對這些對象進行額外的處理或轉換?
請幫助我作為初學者來處理這些問題。 提前致謝!
您可以使用 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})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.