如何在不创建自定义DTO的情况下解析同一JSON请求/响应中的多个对象引发SpringMVC

Mou*_*ssi 1 json spring-mvc jersey

我有两个模型课

  Class User
    {
    }

    Class UserProfile
    {
    }
Run Code Online (Sandbox Code Playgroud)

我想使用SpringMVC和JSON在同一请求/响应中发送/接收(@ GET,@ POST)多个对象。

例如:

{
"userprofile" : { "id":1, name:"test1" },
"user"  : {"id": 161, "name": "x"}
}
Run Code Online (Sandbox Code Playgroud)

Kel*_*cis 5

确保Jackson在类路径中。在您的内部增加一个Controller类似于

static class UserAndProfile {
    public UserProfile userprofile;
    public User user;
}
Run Code Online (Sandbox Code Playgroud)

然后您的请求映射将类似于

@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) {
    ...
}
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请参见使用@ResponseBody注释映射响应主体