1. 程式人生 > >微信小程式-中處理json資料 (從json資料中提取想要的值 將變數json字串轉成json物件)

微信小程式-中處理json資料 (從json資料中提取想要的值 將變數json字串轉成json物件)

1、新增依賴

<dependency>

<groupId>net.sf.json-lib</groupId>

<artifactId>json-lib</artifactId>
<version>2.4</version>

<classifier>jdk15</classifier>

</dependency>

2.操作資料(java後端)

(1)接收其他介面回調回來的資料,並從json資料中提取想要的值

System.out.println(LastResult);

JSONObject jsonObject = JSONObject.fromObject(LastResult);

//通過getString("")分別取出裡面的資訊

String respResult = jsonObject.getString("result");

System.out.println("respResult:"+respResult);

String[] strs = respResult.split("[\"]");

System.out.println("text=" + strs[1]);//strs[1]就是取得JSON裡的result資料

結果:

{"corpus_no":"6584636619263207358","err_msg":"success.","err_no":0,"result":["北京科技館,"],"sn":"855965987821533105182"}

respResult:["北京科技館,"]

text=北京科技館,

(2)將變數json字串轉成json物件

String str = "{\"result\":\""+strs[1]+"\",\"text\":\""+text+"\"}";
JSONObject Object = JSONObject.fromObject(str);
System.out.println(str);

結果:

{"result":"北京科技館,","text": "具體地址在哪裡?"}

然後將json物件放進response

// ------↓返回值給小程式↓------ //

response.setContentType("application/json");

response.setCharacterEncoding("utf-8");

PrintWriter printWriter = response.getWriter();

printWriter.write(Object.toString());

printWriter.flush();

3.微信小程式端

提取資料的寫法:

success: function (res) {

// success 以下是提取非json資料的寫法

var msg = res.data;

console.log('begin');

console.log(msg);

console.log(msg['result']);

console.log(msg['result'][0]);

//-----------以下是提取json資料的寫法

var json1 = JSON.parse(res.data);

console.log(json1);

console.log(json1['result']);

結果:

begin

{"result":"北京科技館,","text":"具體地址在哪裡?"}

undefined

{result: "北京科技館,", text: "具體地址在哪裡?"}

北京科技館,