Spring: return @ResponseBody "ResponseEntity<List<JSONObject>>"
Instead of
return new ResponseEntity<JSONObject>(entities, HttpStatus.OK);
try
return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);
Now I return Object
. I don't know better solution, but it works.
@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity<Object> 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<Object>(entities, HttpStatus.OK);
}
Personally, I prefer changing the method signature to:
public ResponseEntity<?>
This gives the advantage of possibly returning an error message as single item for services which, when ok, return a list of items.
When returning I don't use any type (which is unused in this case anyway):
return new ResponseEntity<>(entities, HttpStatus.OK);