春季:返回@ResponseBody“响应实体<列表<JSONObject>>”
2022-09-01 05:06:45
在控制器中,我创建 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);
}