【发布时间】:2014-12-06 20:15:48
【问题描述】:
在控制器中,我创建了 json 数组。如果我返回List<JSONObject> 就可以了:
@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List<JSONObject> getAll() {
List<Entity> entityList = entityManager.findAll();
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject entity = new JSONObject();
entity.put("id", n.getId());
entity.put("address", n.getAddress());
entities.add(entity);
}
return entities;
}
但我需要返回 JSON 数组和 HTTP 状态码:
@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<List<JSONObject>> getAll() {
List<Entity> entityList = entityManager.findAll();
List<JSONObject> entities = new ArrayList<JSONObject>();
for (Entity n : entityList) {
JSONObject Entity = new JSONObject();
entity.put("id", n.getId());
entity.put("address", n.getAddress());
entities.add(entity);
}
return new ResponseEntity<JSONObject>(entities, HttpStatus.OK); // XXX
}
Eclipse 在 XXX 行看到错误:
Multiple markers at this line
- The constructor ResponseEntity<JSONObject>(List<JSONObject>, HttpStatus) is undefined
- Type mismatch: cannot convert from ResponseEntity<JSONObject> to
ResponseEntity<List<JSONObject>>
- Type mismatch: cannot convert from ResponseEntity<JSONObject> to JSONObject
如何返回json+http回复?我有返回一个 json 对象 + http 状态码的工作代码:
@RequestMapping(value="/{address}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<JSONObject> getEntity(@PathVariable("address") int address) {
Entity n = entityManager.findByAddress(address);
JSONObject o = new JSONObject();
o.put("id", n.getId());
o.put("address", n.getAddress());
return new ResponseEntity<JSONObject>(o, HttpStatus.OK);
}
【问题讨论】:
-
我认为应该是
return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);对吧?无论如何,您下面的解决方案很好。 -
谢谢,它有效。什么是更好的?
ResponseEntity<List<JSONObject>>或ResponseEntity<Object>你有什么意见? -
出于可读性考虑,我认为前者更好。
标签: java json spring rest http-status-codes