微信小程序傳數組(Json字符串)到Java後端

一:小程序端:java

wxml中代碼:json

<!--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中的工具類裏轉化成對應的對象集合:app

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對象集合了須要注意的是:先後端須要約定好數組中傳的字段就是實體類中須要轉化的字段ide

相關文章
相關標籤/搜索