最近在学习微信小程序,遇到了一些坑,有些问题我看官网或者其他博客,可能讲的不是那么易懂,所以自己找到解决方法后,写下来供大家参考,如有不对指出,还恳请大家指出~
比如在实现购物车批量购买的时候,我们需要向后台请求一个list,包含所有勾选的物品信息,在微信小程序里,page里的data是这样定义
data {
orders:[]
}
复制代码
在我们给它赋值后,数据类似于
如果我们利用wx.request把这个list发送的时候,根据微信官方文档的解释:
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)...)
意思就是所有的data数据都会以String类型发送。所以很多朋友可能刚开始和我一样,请求总是错误,或者后台接收了请求,可是值却是null。许多博客给的方法比如
header: {
'content-type': 'application/json'
},
改为
header: {
'content-type': 'application/x-www-form-urlencoded'
},
复制代码
我尝试之后发现请求还是报错,下面给出我的解决方法:
微信小程序:
wx.request({
url: 'http://172.20.10.2:8080/order/wx/buy',
header: {
'content-type': 'application/json'
},
method: "POST",
data:{
buyGoodsDTOS:this.data.orders,
user_id:this.data.user_info.user_id
},
复制代码
data里面有列表类型的orders,以及一个用户ID, 我们就这直接这样发起请求,orders和user_id都会被序列化为json
后台接收
利用阿里的fastjson,我使用的SpringBoot
pom.xml里添加:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
复制代码
Controller里面:
利用fastjson的JSONObject接收wx序列化后的json数据
通过JSONObject类的源码,可以发现他实现类Map接口
public class JSONObject extends JSON implements Map<String, Object>,。。。
复制代码
可以知道,它是利用键值对存储微信小程序发送的json数据,存储方式类似于
JSONArray jsonArray = jsonData.getJSONArray("buyGoodsDTOS"); //根据key名获取
List<BuyGoodsDTO> list = jsonArray.toJavaList(BuyGoodsDTO.class); //将数组对象转化为list,BuyGoodsDTO是与orders里面对象要对应
String user_id = jsonData.get("user_id").toString(); //获取user_id
Integer id = Integer.parseInt(user_id); //转化类型
复制代码