【问题标题】:I am using Postman, to pass the data to a REST api but my variable is showing null value我正在使用 Postman 将数据传递给 REST api,但我的变量显示为空值
【发布时间】:2020-05-14 10:45:27
【问题描述】:

我的主要问题是如何将 (Map, String) 传递给 REST API,我知道如果我使用 @RequestBody 所有传递的内容都存储到 map 但是可以做些什么来传递 map 以及任何其他参数REST API。

@GetMapping(path="/invoices")
public String invoiceReceived( Map<String,Object> invoice,String format) throws MessagingException {
        System.out.println(format); // this prints NULL
        return "returnValue";
}

所以我尝试使用 PathVariable 但它们抛出异常。可以做什么?

@GetMapping(path="/invoices/{invoiceData}/{format}")
public String invoiceReceived(@PathVariable("invoiceData") Map<String,Object> invoice, 
@PathVariable("format") String format) throws MessagingException {
        System.out.println(format); // this prints NULL
        return "returnValue";
}

我应该怎么做才能接受地图和变量作为输入?输入的 JSON 文件应该是什么样子?

   {
        "invoiceData":[{"invoiceId":"23642",
        "clientName":"Client",
        "amount":"23742.67",
        "email":"client@abc.com"
        }],
        "format":"html"
    }

这个问题被确定为与另一个问题相似,所以我试图解释这有什么不同,我知道我可以使用@RequestBody 来获取地图中的所有变量,但是调用将使用两个参数 some其中将存储在地图中,但一个参数将用于另一个变量。那么如何发送地图和其他变量呢?

【问题讨论】:

    标签: java spring api rest


    【解决方案1】:

    我认为您可以使用查询字符串和路径变量。
    如果你声明一个控制器的方法,比如:

    @GetMapping(path="/invoices")
    public String invoiceReceived(@RequestBody Map<String,Object> invoice, @RequestParam String format)  {
      ...
    }
    

    请求发送到的 url 和 JSON 请求正文将如下所示。

    网址:

    http://localhost:8080/invoices?format=html
    

    JSON 请求正文:

    {
      "invoiceId":"23642",
      "clientName":"Client",
      "amount":"23742.67",
      "email":"client@abc.com"
    }
    


    您也可以使用如下路径变量:

    http://localhost:8080/invoices/html
    
    @GetMapping(path="/invoices/{format}“)
    public String invoiceReceived(@RequestBody Map<String,Object> invoice, @PathVariable String format)  {
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2021-04-19
      • 1970-01-01
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      • 2023-03-07
      • 2020-10-30
      相关资源
      最近更新 更多