首页 > 解决方案 > 我正在使用 Postman 将数据传递给 REST api,但我的变量显示为空值

问题描述

我的主要问题是如何将 (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 来获取地图中的所有变量,但是将使用两个参数进行调用,其中一些参数将存储在地图中,但一个参数将用于另一个变量。那么如何发送地图和任何其他变量呢?

标签: javaspringapirest

解决方案


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

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

推荐阅读