我有一些 JSON 对象,它们比我拥有的 java 对象的 JSON 表示形式更复杂。我有构建这些 JSON 对象的方法,我想直接返回并使用它们。我使用 org.json
库来构建我的 JSON。我可以通过将 JSON 对象作为 String
返回来使 GET
方法工作。这是正确的做法吗?
@RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public String getJson() {
JSONObject json = new JSONObject();
JSONObject subJson = new JSONObject();
subJson .put("key", "value");
json.put("key", subJson);
return json.toString();
}
现在我想知道如何使用 JSON 对象?作为字符串并将其转换为 JSON 对象?
@RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
@ResponseBody
public String post(@RequestBody String json) {
JSONObject obj = new JSONObject(json);
//do some things with json, put some header information in json
return obj.toString();
}
这是解决我的问题的正确方法吗?我是新手,所以请指出任何可以做得更好的地方。请注意:我不想返回 POJO。
最佳答案
我认为使用 jackson 库您可以执行以下操作。
@RequestMapping(value = "/getjson", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public String getJson() {
//your logic
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(json);
}
@RequestMapping(value = "/post", method = RequestMethod.POST, produces="application/json", consumes="application/json")
@ResponseBody
public String post(@RequestBody String json) {
POJO pj = new POJO();
ObjectMapper mapper = new ObjectMapper();
pj = mapper.readValue(json, POJO.class);
//do some things with json, put some header information in json
return mapper.writeValueAsString(pj);
}
关于java - 在 Spring RESTful 服务中生成和使用自定义 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26115076/