微信小程序传数组(Json字符串)到Java后端

一:小程序端:

wxml中代码:

技术分享图片
技术分享图片

<!--index.wxml--><view> <view> <button bindtap="onShow"> 调接口 </button> </view></view>

View Code

js中代码:

技术分享图片
技术分享图片

//index.js//获取应用实例const app = getApp()Page({ onShow:function(){ console.log(‘123456‘) let newDate={ a:JSON.stringify([{a:1,b:2},{a:3,b:2}]) } wx.request({ url: ‘http://10.0.1.183:8080/aone_sg/wx/aaa.action‘, method:‘POST‘, data: {a:newDate.a}, header:{ ‘Content-Type‘:‘application/x-www-form-urlencoded;charset=utf-8‘ }, success(res){ console.log(res) } }) }})

View Code

二:Java后端:

调用的接口代码:

技术分享图片
技术分享图片

private String a;//入参数组转成的json格式的字符串 @Action(value="aaa")public void aaa() throws IOException{ System.out.println("进入"); System.out.println(a); TestDemo.bbbb(a);}//get/set.......

View Code

入参Json字符串(数组)在bean中的工具类里转化成对应的对象集合:

技术分享图片
技术分享图片

package com.aone.foottalk.common;import java.util.List;import net.sf.json.JSONArray;public class TestDemo { private String a; private String b; public String getA() { return a; } public void setA(String a) { this.a = a; } public String getB() { return b; } public void setB(String b) { this.b = b; } @SuppressWarnings("unchecked") public static void bbbb(String a){ //转对象集合 JSONArray json = JSONArray.fromObject(a); List<TestDemo> list = (List<TestDemo>)JSONArray.toCollection(json, TestDemo.class); list.forEach(f->{ System.out.println(f.getA()+"***"+f.getB()); }); } }

View Code

小程序传的数组此时就变成后端拿到的List对象集合了需要注意的是:前后端需要约定好数组中传的字段就是实体类中需要转化的字段

 

相关文章