微信小程式傳陣列(Json字串)到Java後端
阿新 • • 發佈:2019-01-03
一:小程式端:
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 newDateView Code={ 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) } }) } })
二: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物件集合了需要注意的是:前後端需要約定好陣列中傳的欄位就是實體類中需要轉化的欄位