简体   繁体   English

我们如何在SpringBoot中使用@RequestBody传递列表和单独的字符串

[英]How can we pass a List and a separate String using @RequestBody in SpringBoot

I have written this code but getting Status: 400 Bad Request error in JSON 我已经编写了这段代码,但状态为: JSON出现400 Bad Request错误

@CrossOrigin
    @PostMapping(value = "/retail/scorecard/addKPI", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public @ResponseBody Object addKpi(@Valid @RequestParam List<KPIReq> kpiReqList,@RequestParam("goalId") String goalId,
        HttpServletRequest req, HttpServletResponse res) throws RecordNotFoundException, Exception {

Use @Valid @RequestBody List<KPIReq> kpiReqList for your list. 使用@Valid @RequestBody List<KPIReq> kpiReqList作为列表。 May be an error in your json. 可能是您的json中的错误。

The Request param essentially maps parts of the request uri to an object. Request参数本质上将请求uri的一部分映射到一个对象。 Like for uri: 像uri:

http://localhost/api/v1/search?type=11&type=12&color=RED&color=GREY

you could map it like : 你可以像这样映射它:

        public @Responsebody Object addKpi(
        @RequestParam(value="type", required=false) List<String> types,
        @RequestParam(value="color", required=false) List<String> colors)
        {
            ....
        }

Instead of passing the List as a RequestParam , why don't you try providing it as part of the request body. 而不是将List作为RequestParam传递,为什么不尝试将其作为请求正文的一部分提供。 Complex objects are better to be send as request body.Like: 复杂对象最好作为请求正文发送。

    @CrossOrigin
    @PostMapping(value = "/retail/scorecard/addKPI", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public @ResponseBody Object addKpi(@Valid @RequestBody List<KPIReq> kpiReqList,@RequestParam("goalId") String goalId,
            HttpServletRequest req, HttpServletResponse res) throws RecordNotFoundException, Exception {

Your error is 400 bad request that's mean your function with an object with type X but don't receive it, Can you try to add the name for you 您的错误是400错误的请求,这意味着您的函数具有类型X的对象,但没有收到,您​​能尝试为您添加名称吗

 @RequestParam(name = "kpiReqList")  
 @RequestParam(name ="goalId")

which the type of the list and the id Json or XML? 列表的类型以及ID Json或XML?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM