【问题标题】:Request String [] + String as Json from rest controller method从休息控制器方法请求 String [] + String as Json
【发布时间】:2019-03-30 02:54:44
【问题描述】:

我一直在这里寻找解决方案,但没有发现对我的情况有用。

我的 Dao 需要一个 String[] 和一个 String,所以我这样做了:

@RequestMapping(value = "/add", method = RequestMethod.POST, consumes = { "application/json" })
public void newRent(@RequestBody String[] isbn,String username) {
    rentService.newRent(isbn, username);
}

现在,我正在尝试从 Postman 调用映射链接的POST,但我不断获取不允许的方法 (405)。

我尝试了很多,这看起来是最好的方法,但仍然不起作用。

[
 { {   "isbn":"123"},{"isbn":"1234"},
 { "username" : "zappa"}
]

{
  "isbn": ["123", "1234"],
  "username": "zappa"
}

我错过了什么吗?想不通!

【问题讨论】:

    标签: java json spring rest spring-mvc


    【解决方案1】:

    你必须创建一个新实体Rent

    public class Rent{public string[] isbn; public string username;}
    

    然后您将方法更改为:

     @RequestMapping(value = "/add", method = RequestMethod.POST, consumes = { "application/json" })
    public void newRent(@RequestBody Rent rentRequest) {
        rentService.newRent(rentRequest.isbn, rentRequest.username);
    }
    

    【讨论】:

      【解决方案2】:

      首先,这是正确的 JSON(另一个不正确,check it here):

      {
        "isbn": ["123", "1234"],
        "username": "zappa"
      }
      

      现在,为了获得这些值,您需要使用@RequestBody 以及一些POJOJavaBeanMap,以便正确获得这些值。例如,使用 Map 会是这样的:

      @RequestMapping(value = "/add", method = RequestMethod.POST, consumes = { "application/json" })
      public void newRent(@RequestBody Map data) {
          rentService.newRent((String [])data.get("isbn"), data.get("username").toString());
      }
      

      使用 POJO,它会是这样的:

      public class RentEntity {
          private String[] isbn;
          private String username;
      
          public String[] getIsbn() {
              return isbn;
          }
      
          public void setIsbn(String[] isbn) {
              this.isbn = isbn;
          }
      
          public String getUsername() {
              return username;
          }
      
          public void setUsername(String username) {
              this.username = username;
          }
      }
      
      @RequestMapping(value = "/add", method = RequestMethod.POST, consumes = { "application/json" })
      public void newRent(@RequestBody RentEntity data) {
          rentService.newRent(data.getIsbn(), data.getUsername());
      }
      

      其他信息

      【讨论】:

        猜你喜欢
        • 2017-10-25
        • 1970-01-01
        • 2016-11-06
        • 1970-01-01
        • 1970-01-01
        • 2015-11-24
        • 1970-01-01
        • 1970-01-01
        • 2013-08-19
        相关资源
        最近更新 更多