微信小程序傳數組(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對象集合了需要注意的是:前后端需要約定好數組中傳的字段就是實體類中需要轉化的字段

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM