我有一些JSON对象,它们比我拥有的Java对象的JSON表示更为复杂。我有构建这些JSON对象的方法,我想直接返回并使用它们。我使用org.json
库来构建JSON。我可以GET
通过将JSON对象返回为来使该方法正常工作String
。这是正确的方法吗?
@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。
我认为使用杰克逊图书馆,您可以执行以下操作。
@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);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句