java - 向 ResponseBody 对象添加附加属性

标签 java json spring-mvc

我有以下 Spring @RestController 方法

@RequestMapping(value = "/getPeople", method = RequestMethod.GET)
public List<Person> getPeople(Model model){
    List<People> people = personRepo.getAllPeople();
    model.addAttribute("people", people);
    return people;
}

它将以下内容返回到响应正文

[
    {"name":"Jim","group":1},
    {"name":"Dwight","group":2},
    {"name":"Stanley","group":3}
]

我可以修改此方法(通过 @Controller 方法本身,或使用 AJAX 请求)以包含 people 数组内部或外部的其他属性吗?并且不修改 Person 对象 - 以便返回的对象看起来像

{
    "people":[
        {"name":"Jim","group":1, "independentAttribute": "A"},
        {"name":"Dwight","group":2, "independentAttribute": "B"},
        {"name":"Stanley","group":3, "independentAttribute": "C"}
    ],
    "extraAttributes":[
        {"attribute1": 1,"attribute2": 2,"attribute3":3}
    ]
}

如果这不是有效的对象/数组语法,我很抱歉,懒洋洋地把它放在一起。

最佳答案

您可以在JSON请求的回调中修改该对象。我不熟悉 d3_json 但你可以这样做

callback : function(data){
   //data is the returned List<Person> serialized to JSON
   var modifiedObj = new Object();
   modifiedObj.persons = data;
   modifiedObj.extraAttributes = [{"attribute1": 1,"attribute2": 2,"attribute3":3}]
}

关于java - 向 ResponseBody 对象添加附加属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33090312/

相关文章:

android - Android中解析WordPress JSON API

javascript - 适用于 Spring Roo/Web MVC 项目的漂亮 javascript 多选小部件?

java - spring中@Configuration类的作用域

java - JQuery Ajax 使用 success() 回调进行空响应

java - 对于 JDBC 操作,Spring 是否过于复杂?

java - 如何在Spring中使用@Transactional实现真正的事务

javascript - 将两个 json 对象数据合并为一个,JSON 为新的 Single JSON,

mysql - 当文档包含 json_string 作为 mysql 5.7 中的值时,插入 json 列时出现错误

java - Fat Jar中的Apache Camel Timer Nullpointer异常

java - 声音处理 - Android 上的节拍匹配音乐播放器