起因
在写毕业设计的wx小程序时,不知道怎么接收小程序提交的对象数组,看到网上直接把json的string转为List后却提示了错误,然后就打印了一下结果,正好自己也没写过markdown,顺便学习一下语法,尝试记录一下。
微信开发文档的data 参数说明
最终发送给服务器的数据是 String 类型,如果传入的 data 不是 String 类型,会被转换成 String 。转换规则如下:
对于
GET
的数据,会将数据转换成query string
(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)
对于POST
方法且header['content-type']
为application/json
的数据,会对数据进行 JSON 序列化。
对于POST
方法且header['content-type']
为application/x-www-form-urlencoded
的数据,会将数据转换成 query string
(encodeURIComponent(k)=encodeURIComponent(v)&encodeURIComponent(k)=encodeURIComponent(v)…)
代码
在接受参数的后,在java打印时json时发现String格式为"json":[{"id":"1","number":1,"checked":false}{"id":"20191126102608130778","number":1,"checked":true},{"id":"20191126102608130778","number":1,"checked":true}]
,
将string转为JSONObject后,通过key取出JSONArray,在将JSONArray转为JavaList.
后面写了一会儿代码后,突然意识到小程序中直接提交数据的话,在后段可以直接用JSONArray接收。
java后端
//使用了fastjson转化
@PostMapping("cart/update")
@ResponseBody
public Message updateCartList(@RequestBody JSONArray jsonArray){
System.out.println(jsonArray);
List<Cart> cartList = jsonArray.toJavaList(Cart.class);
System.out.println("更新cart:"+cartList);
for(Cart cart : cartList){
// System.out.println(cart);
cartService.updateCart(cart);
}
Message result = new Message();
result.setFlag(true);
result.setCode("更新cart:"+cartList);
return result;
}
小程序
//json为对象数组{id,number,checked}
wx.request({
url: app.globalData.url+'/cart/update',
data: jsonCartList,
method: 'POST', // OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT
// header: {}, // 设置请求的 header
success: function(res){
var msg = res.data;
},
})