package com.zjw.mynetwork6; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; //9.4 p329 解析JSON格式数据 /* 比起XML,JSON的主要优势在于它的体积更小,在网络上传输的时候可以省流量 缺点在于,它的语义性较差,看起来不如XML直观 */ /*在服务器准备一份json文件, 原生模拟器访问地址:http://10.0.2.2:8080//get_data.json 浏览器访问地址:http://localhost:8080//get_data.json */ /* get_data.json [{"id":"5","version":"5.5","name":"Clash of Clans"}, {"id":"6","version":"7.0","name":"Boom Beach"}, {"id":"7","version":"3.5","name":"Clash Royale"}] */ //9.4.1 p330 使用JSONObject //解析JSON数据方法:官方:JSONObject,谷歌开源库GSON,第三方开源库Jackson,FastJSON…… //把OkHttp的使用的代码拷一份过来(笔记(8)) public class JSONObjectAnalysisOfJSON extends AppCompatActivity { private Button mBtnSendRequest; private TextView mTvResponseText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jsonobject_analysis_of_json); //找到控件 mBtnSendRequest = (Button) findViewById(R.id.btn_send_request); mTvResponseText = (TextView) findViewById(R.id.tv_response_text); //Button点击事件,发送HTTP请求 mBtnSendRequest.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //用OkHttp发送HTTP请求 sendRequestWithOkHttp(); } }); } private void sendRequestWithOkHttp() { //开启新线程做耗时操作 new Thread(new Runnable() { @Override public void run() { try { OkHttpClient client = new OkHttpClient();//创建一个OkHttpClient实例 Request request = new Request.Builder() .url("http://10.0.2.2:8080//get_data.json")//设置目标网络地址 .build();//创建一个Request对象 Response response = client.newCall(request).execute();//发送请求获取服务器返回对象 String responseData=response.body().string(); paraJSONWithJSONObject(responseData); } catch (IOException e) { e.printStackTrace(); } } }).start(); } private void paraJSONWithJSONObject(String responseData) { StringBuilder builder = new StringBuilder(); try { JSONArray jsonArray=new JSONArray(responseData); for(int i=0;i<jsonArray.length();i++){ JSONObject jsonObject=jsonArray.getJSONObject(i); String id=jsonObject.getString("id"); String name=jsonObject.getString("name"); String version=jsonObject.getString("version"); builder.append("id:" + id + "\n") .append("name:" + name + "\n") .append("version:" + version + "\n") .append("-----------------------------\n"); } showResponse(builder.toString()); } catch (JSONException e) { e.printStackTrace(); } } //将数据设置给TextView private void showResponse(final String s) { //在UI线程(主线程)更新UI,因为Android不允许在子线程中进行UI操作 runOnUiThread(new Runnable() { @Override public void run() { mTvResponseText.setText(s); } }); } }
转载于:https://my.oschina.net/u/3620480/blog/1489812