1、添加依賴
使用 阿里雲倉庫 http://maven.aliyun.com/nexus/#welcome
maven 配置阿里雲倉庫: http://blog.csdn.net/only_wan/article/details/52975698
<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: "具體地址在哪里?"}
北京科技館,