我有两个模型类
Class User
{
}
Class UserProfile
{
}
我想使用SpringMVC和JSON在同一请求/响应中发送/接收(@ GET,@ POST)多个对象。
例如:
{
"userprofile" : { "id":1, name:"test1" },
"user" : {"id": 161, "name": "x"}
}
答案 0 :(得分:5)
确保Jackson位于类路径中。在Controller
中创建一个类似于
static class UserAndProfile {
public UserProfile userprofile;
public User user;
}
然后您的请求映射类似于
@RequestMapping(value = "/user", method = RequestMethod.GET)
public @ResponseBody UserAndProfile user() {
UserAndProfile userAndProfile = new UserAndProfile();
userAndProfile.userprofile = ...
userAndProfile.user = ...
return userAndProfile;
}
@RequestMapping(value = "/user", method = RequestMethod.POST)
public Object user(@RequestBody UserAndProfile userAndProfile) {
...
}
有关详细信息,请参阅Mapping the response body with the @ResponseBody annotation。