我正在使用Spring MVC
并返回JSON
作为回复。我想创建一个通用的JSON
响应,我可以放入任何TYPE并希望响应看起来像这样
{
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
控制器中使用此Response对象返回空响应对象和/或填充的响应对象。先谢谢GM
更新
为了获得与所描述的输出相似的JSON
输出,即JSON
中的“accounts”键,我必须在控制器中使用以下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
输出中的“帐户”键?
答案 0 :(得分:0)
虽然您的示例JSON无效(status
且data
未包含在引号中),但此方法仍然有效。
你需要确保在你的课程路径上有杰克逊罐子,而春天会照顾其余的。
为了使其工作,我将为您的响应类创建一个类似于以下内容的构造函数:
public class Response<T> {
private String status;
private String message;
private T data;
public Response(String status, String message, T data) {
this.status = status;
this.message = message;
this.data = data;
}
//...getter methods here
}
然后在Spring控制器中,只需从用@RequestMapping
@Controller
public class MyController {
@RequestMapping(value="/mypath", produces="application/json")
public Response<SomeObject> myPathMethod() {
return new Response<SomeObject>("200", "success!", new SomeObject());
}
}