简体   繁体   中英

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

@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. May be an error in your json.

The Request param essentially maps parts of the request uri to an object. Like for 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. 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

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

which the type of the list and the id Json or XML?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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