解析JSON

来源:互联网 发布:模拟器mac版 编辑:程序博客网 时间:2024/06/08 09:49

运行截图
这里写图片描述
这里写图片描述

MainActivity.java

package csdn.example.com.notification.NetWorkTest;import android.os.Bundle;import android.support.v7.app.AppCompatActivity;import android.util.Log;import android.view.View;import android.widget.Button;import android.widget.TextView;import org.json.JSONArray;import org.json.JSONObject;import org.xml.sax.InputSource;import org.xml.sax.XMLReader;import java.io.IOException;import java.io.StringReader;import javax.xml.parsers.SAXParserFactory;import csdn.example.com.notification.R;import okhttp3.OkHttpClient;import okhttp3.Request;import okhttp3.Response;public class Main6Activity extends AppCompatActivity implements View.OnClickListener {    TextView request_text;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main6);        request_text = (TextView) findViewById(R.id.request_text);        Button send_Request = (Button) findViewById(R.id.send_request);        send_Request.setOnClickListener(this);    }    @Override    public void onClick(View v) {        if(v.getId() == R.id.send_request){            Log.d("T","没毛病,老铁");            //sendRequestWithHttpURLConnection();            sendRequestWithOkHttp();        }    }    private void sendRequestWithOkHttp() {        new Thread(new Runnable() {            @Override            public void run() {                try {                    OkHttpClient client = new OkHttpClient();                    Request request = new Request.Builder()                            .url("http://10.7.90.163:8088/get_data.json")                            .build();                    Response response = client.newCall(request).execute();                    String requestData = response.body().string();                    //parseXMLWithPull(requestData);                    //parseXMLWithSAX(requestData);                    parseJSONWithJSONObject(requestData);                    showResponse(requestData);                } catch (IOException e) {                    e.printStackTrace();                }            }        }).start();    }    private void parseJSONWithJSONObject(String jsonData) {        try {            JSONArray jsonArray = new JSONArray(jsonData);            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");                Log.i("Main6","id is "+id);                Log.i("Main6","name is "+name);                Log.i("Main6","version is "+version);            }        } catch (Exception e) {            e.printStackTrace();        }    }    private void parseXMLWithSAX(String xmlData) {        try {            SAXParserFactory factory = SAXParserFactory.newInstance();            XMLReader xmlReader = factory.newSAXParser().getXMLReader();        ContentHandler handler = new ContentHandler();            //将ContentGandler中的实例设置到XMLReader中            xmlReader.parse(new InputSource(new StringReader(xmlData)));        } catch (Exception e) {            e.printStackTrace();        }    }    private void showResponse(final String response) {       runOnUiThread(new Runnable() {           @Override           public void run() {               Log.d("T","没毛病,老铁1"+response);               request_text.setText(response);           }       });    }}

ContentHandler.java

package csdn.example.com.notification.NetWorkTest;import android.util.Log;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;/** * Created by 王德强 on 2017/7/24. */public class ContentHandler extends DefaultHandler {    private String nodeName;    private StringBuilder id;    private StringBuilder name;    private StringBuilder version;    @Override    public void startDocument() throws SAXException {        id = new StringBuilder();        name = new StringBuilder();        version = new StringBuilder();    }    @Override    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {        //记录当前节点名        nodeName = localName;    }    @Override    public void characters(char[] ch, int start, int length) throws SAXException {        //根据当前节点名判断将内容添加到哪一个StringBuilder对象中        if("id".equals(nodeName)){            id.append(ch,start,length);        }else if("name".equals(nodeName)){            name.append(ch,start,length);        }else if("version".equals(nodeName)){            version.append(ch,start,length);        }    }    @Override    public void endElement(String uri, String localName, String qName) throws SAXException {        if("app".equals(localName)){            Log.d("ContentHandler","id is "+id.toString().trim());            Log.d("ContentHandler","name is "+name.toString().trim());            Log.d("ContentHandler","version is "+version.toString().trim());            //最后要将StringBuilder清空掉            id.setLength(0);            name.setLength(0);            version.setLength(0);        }    }}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout    android:orientation="vertical"    android:layout_width="match_parent"    android:layout_height="match_parent"    xmlns:android="http://schemas.android.com/apk/res/android">    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:id="@+id/send_request"        android:text="发送请求"        />    <ScrollView        android:layout_width="match_parent"        android:layout_height="match_parent"        android:background="@color/colorAccent"        >        <TextView            android:background="@color/colorPrimary"            android:id="@+id/request_text"            android:layout_width="match_parent"            android:layout_height="wrap_content" />    </ScrollView></LinearLayout>
原创粉丝点击