Spring: return @ResponseBody "ResponseEntity>" Spring:返回 @ResponseBody "ResponseEntity>"

19 浏览
0 Comments

Spring: return @ResponseBody "ResponseEntity>" Spring:返回 @ResponseBody "ResponseEntity>"

在控制器中,我创建了一个JSON数组。如果我返回List,那么没问题:

@RequestMapping(value="", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody List getAll() {
    List entityList = entityManager.findAll();
    List entities = new ArrayList();
    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> getAll() {
    List entityList = entityManager.findAll();
    List entities = new ArrayList();
    for (Entity n : entityList) {
        JSONObject Entity = new JSONObject();
        entity.put("id", n.getId());
        entity.put("address", n.getAddress());
        entities.add(entity);
    }
    return new ResponseEntity>(entities, HttpStatus.OK); // XXX
}

Eclipse在XXX行显示错误:

Multiple markers at this line
    - The constructor ResponseEntity(List, HttpStatus) is undefined
    - Type mismatch: cannot convert from ResponseEntity to 
     ResponseEntity>
    - Type mismatch: cannot convert from ResponseEntity to JSONObject

我如何返回JSON和HTTP响应?这是我用于返回一个JSON对象和HTTP状态码的工作代码:

@RequestMapping(value="/{address}", method=RequestMethod.GET, produces=MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody ResponseEntity 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(o, HttpStatus.OK);
}

0