>"-6ren"> >"-在 Controller 中,我创建了 json 数组。如果我返回 List没关系: @RequestMapping(value="", method=RequestMethod.GET, produ-6ren">
gpt4 book ai didi

java - Spring :返回@ResponseBody "ResponseEntity>"

转载 作者:IT老高 更新时间:2023-10-28 12:49:46 26 4
gpt4 key购买 nike

在 Controller 中,我创建了 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<JSONObject>(entities, HttpStatus.OK);

试试

return new ResponseEntity<List<JSONObject>>(entities, HttpStatus.OK);

关于java - Spring :返回@ResponseBody "ResponseEntity<List<JSONObject>>",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26320106/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com