Springboot项目中Controller接受List<Object>参数

控制器接受复杂参数的方法

最近在写一个微信小程序的request请求时发现后端一直报错,似乎是因为前端发送的数组参数和后端接受的参数List<Integer>不能对应上,在网上搜了很多方法都不能解决问题,换一种解决方案就换一个报错,包括但不限于

No primary or single unique constructor found for interface java.util.List

org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type java.util.ArrayList<java.lang.Integer> from Object value (token JsonToken.START_OBJECT); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize value of type java.util.ArrayList<java.lang.Integer> from Object value (token JsonToken.START_OBJECT) at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 1, column: 1]]

等各种报错,期间不停换用content-typeJSON.stringify以及后端阿里的Fastjson等各种解决方案,都没有解决问题。不过最后还是参考了一篇博文,通过解决新建一个数据对象解决了问题,还是经验太少了,以后有机会还是要学习一下其他的解决方法。

用数据类的方法传递复杂参数

新建一个数据类用于传递参数

public class TheIDList implements Serializable {
    
    
	//这里我只用到一个List<Integer>参数,故这个数据类只写了一个属性
	//如果有需要的话可以自定义其他数据类型如Map等
    private List<Integer> idList;

    public List<Integer> getIdList() {
    
    
        return idList;
    }
    public void setIdList(List<Integer> idList) {
    
    
        this.idList = idList;
    }
}

Controller

    @PostMapping("/test")
    @ResponseBody
    public Returntype methodName(@RequestBody TheIDList theIDList ){
    
    
        List<Integer> intList = theIDList.getIDList();
        ***
        methodbody
        ***
        return returntype 
    }

微信小程序前端代码

    wx.request({
    
    
      url: 'http://localhost:8080/test',
      method: 'POST',
      header: {
    
    
        'content-type': 'application/json'
        },
      data:{
    
    
      	//这里idList与数据类中的属性对应
        idList:IDList
      },
      success : function(res){
    
    
      	console.log("success")
        })
      }
    })

所用方法参考了以下文章
https://blog.csdn.net/Tach1banA/article/details/118581214

猜你喜欢

转载自blog.csdn.net/qq_51330798/article/details/130312999