我正在使用Spring MVC
并返回JSON
作为响应。我想创建一个通用的JSON
响应,我可以把任何类型和要应对这个样子spring generic json响应
{
status : "success",
data : {
"accounts" : [
{ "id" : 1, "title" : "saving", "sortcode" : "121212" },
{ "id" : 2, "title" : "current", "sortcode" : "445566" },
]
}
}
所以我创建了一个Response<T>
对象
public class Response<T> {
private String status;
private String message;
T data;
...
...
}
- 这是正确的这样做的方式,还是有更好的方法?
- 如何使用此响应对象在
Spring
控制器中返回空响应对象和/或填充的响应对象。提前
感谢GM
UPDATE:
为了获得类似JSON
输出所描述的,即以“帐户”键JSON
,我不得不使用Response<Map<String, List<Account>>>
的以下在控制器中:
@RequestMapping(value = {"/accounts"}, method = RequestMethod.POST, produces = "application/json", headers = "Accept=application/json")
@ResponseBody
public Response<Map<String, List<Account>>> findAccounts(@RequestBody AccountsSearchRequest request) {
//
// empty accounts list
//
List<Account> accountsList = new ArrayList<Account>();
//
// response will hold a MAP with key="accounts" value="List<Account>
//
Response<Map<String, List<Account>>> response = ResponseUtil.createResponseWithData("accounts", accountsList);
try {
accountsList = searchService.findAccounts(request);
response = ResponseUtil.createResponseWithData("accounts", accountsList);
response.setStatus("success");
response.setMessage("Number of accounts ("+accounts.size()+")");
} catch (Exception e) {
response.setStatus("error");
response.setMessage("System error " + e.getMessage());
response.setData(null);
}
return response;
}
这是否正确吗?即为了获得JSON
输出中的“账户”密钥?
这是一个有用的共同响应实体。 – Wuaner