【发布时间】:2010-11-18 05:46:36
【问题描述】:
如何生成 JqGrid 所需的相同 JSON 格式:
现在我的 Spring Controller 能够产生以下 JSON 输出:
{
"records":"5",
"total":"20",
"page":"1"
"rows":[
{"id":"1","cell":["1","john","smith"]},
{"id":"2","cell":["2","jane","adams"]}
]
}
这是产生该输出的 Spring Controller 方法:
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody getUsers viewUsersAsJSON() {
logger.debug("Retrieving all users as JSON");
UsersJsonDTO usersJsonDTO = new UsersJsonDTO();
usersJsonDTO.setPage("1");
usersJsonDTO.setRecords("5");
usersJsonDTO.setTotal("20");
ArrayList<RowJson> rowJsonList = new ArrayList<RowJson>();
for (UserRoleDTO userRoleDTO:userRoleServiceFacade.getAll()) {
RowJson rowJson = new RowJson();
rowJson.setId(userRoleDTO.getId().toString());
rowJson.setCell(userRoleDTO.getFirstName());
rowJson.setCell(userRoleDTO.getLastName());
rowJsonList.add(rowJson);
}
usersJsonDTO.setRows(rowJsonList);
return usersJsonDTO;
}
这里是 UsersJsonDTO:
public class UsersJsonDTO {
private String page;
private String total;
private String records;
private ArrayList<RowJson> rows;
...getters/setters etc...
}
这是 RowJson:
public class RowJson {
private String id;
private List<String> cell;
public RowJson() {
cell = new ArrayList<String>();
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<String> getCell() {
return cell;
}
public void setCell(String cell) {
this.cell.add(cell);
}
}
这些是生成我在本问题开头给出的示例输出所需的类。 @ResponseBody 自动将返回的对象转换为 JSON。见Spring Ajax Simplifications 3.0
我想要一个更干净、更简单的实现。我想要这样的东西(当然,我试过这个但它没有给出正确的输出):
@RequestMapping(value = "/json", method = RequestMethod.GET)
public @ResponseBody getUsers viewUsersAsJSON() {
logger.debug("Retrieving all users as JSON");
UsersJsonDTO usersJsonDTO = new UsersJsonDTO();
usersJsonDTO.setPage("1");
usersJsonDTO.setRecords("5");
usersJsonDTO.setTotal("20");
usersJsonDTO.setRows(userRoleServiceFacade.getAll());
return usersJsonDTO;
}
有什么想法吗?感谢您的宝贵时间。
我也希望能够输出以下格式:
{
"records":"5",
"total":"20",
"page":"1"
"rows":[
{"id":"1","cell":["id":"1","name":"john","lastname":"smith"]},
{"id":"2","cell":["id":"2","name":"jane","lastname":"adams"]}
]
}
但是,当我尝试这样做时,我得到了以下额外的花括号(在单元格和 id 之间):
{
"records":"5",
"total":"20",
"page":"1"
"rows":[
{"id":"1","cell":[{"id":"1","name":"john","lastname":"smith"}]},
{"id":"2","cell":[{"id":"2","name":"jane","lastname":"adams"}]}
]
}
很多问题,但我认为它们是相关的。
【问题讨论】:
标签: jquery json spring jqgrid response