【问题标题】:how to pass custom dto as rest api input using postman rest client如何使用邮递员休息客户端将自定义 dto 作为休息 api 输入传递
【发布时间】:2019-08-03 19:27:41
【问题描述】:

这是我的代码,我正在尝试将用户详细信息作为 json 输入传递,但我无法在我的 rest api 方法中接收数据。我将所有值都设为空,

这是我的 json 请求

{
    "userId" : "12345",
    "username" : "arun.ammasai",
    "createdBy" : "-2",
    "updatedBy" : "-2",
    "statusCd" : "New",
    "createdDate" : "2019-03-03",
    "updatedDate" : "2019-03-03"
}

================================================ ======================

@RequestMapping(value = "/registerUser", method = RequestMethod.POST, consumes = { "application/JSON", "application/XML" })
private String registerUser(User user) {
    System.out.println(user.toString());
    return "User Created";
}

================================================ ======================

这是 Postman Client 中的响应

意外的“U”

【问题讨论】:

  • 请发布完整的邮递员请求,包括标题
  • 我正在使用我的 localhost ,并且标头包含 application/JSON, application/XML
  • 所以你有名称 Content-Type 和值 application/JSON 的标题?

标签: java json rest api spring-mvc


【解决方案1】:

使用@RequestBody 注解更新您的方法签名。它会自动将您的 json 反序列化为 java 实体。请注意,json 中的名称应与 User 对象中的参数相同,并且 User 对象应具有 getter 和 setter。所以你的方法应该看起来像

    @RequestMapping(value = "/registerUser", method = RequestMethod.POST, consumes = { "application/JSON", "application/XML" })
        private String registerUser(@RequestBody User user) {
            System.out.println(user.toString()); //What is the reason of doing toString of java Object? 
            //better to do System.out.println(user.getUsername())
            return "User Created";
    }

【讨论】:

    猜你喜欢
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-06
    • 2014-11-17
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多