从其余控制器方法请求String [] +作为Json的String

时间:2018-10-25 13:15:08

标签: java json spring rest spring-mvc

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

我的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"
}

我想念什么吗?无法弄清楚!

2 个答案:

答案 0 :(得分:2)

您必须创建一个新实体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);
}

答案 1 :(得分:0)

首先,这是正确的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());
}

其他信息