在控制器中,我创建jsonarray.如果我返回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);
}

推荐答案

现在我返回Object.我不知道更好的解决方案,但它是有效的.

@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);
}

Json相关问答推荐

Terraform迭代JSON文件以获取键值对

当有2个嵌套数组时展平复杂的JSON

通过在织女星简化图上裁剪来显示文本

给定一个包含两个数组的JSON输入文件,如何使用Jolt将一个数组中的每个元素与另一个数组组合在一起?

合并2个嵌套词典

在Snowflake中查询JSON时,属性名称是否支持绑定参数?

使用 jq 重新格式化 JSON 输出

将 std::可选值存储到 json 文件 C++

如何使用jolt将嵌套数据变成线性数据

如何加入或合并列表元素列表(未知长度)

在 JOLT 中重新排列值

将文本转换为 python 列表

在 postgresql 中将行转换为 json 对象

使用 System.Text.Json 序列化记录成员

如何一次加载无限滚动中的所有条目以解析python中的HTML

如何在 json 编码字符串内的子数组数据周围添加方括号?

如何在 Python 中合并两个 json 字符串?

JSON JQ 如果没有 else

雅虎财经全币种报价 API 文档

设置对象不是 JSON 可序列化的