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

 可以吸的果冻Ci 发布于 2023-02-11 19:54

我有两个模型课

  Class User
    {
    }

    Class UserProfile
    {
    }

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

例如:

{
"userprofile" : { "id":1, name:"test1" },
"user"  : {"id": 161, "name": "x"}
}

Kelsey Franc.. 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) {
    ...
}

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

撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有