1. 程式人生 > >Android—(獲取並解析xml和Json)

Android—(獲取並解析xml和Json)

思維導圖:


           Android的網路程式設計中去拿伺服器的資料,一般只採用兩種方式。XML和Json,所以今天我們簡單做一個案列示範,

其他複雜的都離不開這最基礎的步驟。

效果圖:

佈局:


輸出結果:

 xml解析


json解析


  第一步:我們需要xml檔案和JSON檔案(原始檔放在伺服器上面)(實際專案開發中我們是動態生成的) 

①student.xml

<?xml version="1.0" encoding="UTF-8"?>
 <students>
     <student sid="1">
      <sname>碼農01</sname>
      <sage>101</sage>
     </student>
	   <student sid="2">
      <sname>碼農02</sname>
      <sage>102</sage>
     </student>
	   <student sid="3">
      <sname>碼農03</sname>
      <sage>103</sage>
     </student>
 </students>


②students.json

{"count":3,"students":[{"sid":1,"sname":"小小","ssex":"女"},{"sid":2,"sname":"小碼","ssex":"男"},{"sid":3,"sname":"小農","ssex":"男"}]}

第二步: 寫好佈局檔案
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.android31_xmlorjson.MainActivity">


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="獲取網路xml"
        android:onClick="getNetXml"
        />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="獲取網路JSON"
        android:onClick="getNetJSON"
        />


</LinearLayout>


第三步:核心處理類

注意:

 1、手機獲取服務端資料需要在AndroidManifest.xml配上許可權

<!--網路許可權-->
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
2、JSON解析所需要用的實體類

BigObject.java

package com.example.android31_xmlorjson;

import java.util.List;

/**
 * Created by Administrator on 2017/7/26 0026.
 */

public class BigObject {
    private int count;
    private List<Student> students;

    public BigObject() {
    }
    public BigObject(int count, List<Student> students) {
        this.count = count;
        this.students = students;
    }
    public void setCount(int count) {
        this.count = count;
    }

    public void setStudents(List<Student> students) {
        this.students = students;
    }

    public int getCount() {
        return count;
    }

    public List<Student> getStudents() {
        return students;
    }


}
student.java
package com.example.android31_xmlorjson;

/**
 * Created by Administrator on 2017/7/26 0026.
 */

public class Student {
    private int sid;
    private String sname;
    private String ssex;

    public Student() {

    }

    public Student(int sid, String sname, String sex) {
        this.sid = sid;
        this.sname = sname;
        this.ssex = ssex;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public void setSsex(String ssex) {
        this.ssex = ssex;
    }

    public int getSid() {
        return sid;
    }

    public String getSname() {
        return sname;
    }

    public String getSsex() {
        return ssex;
    }
}

3.JSON解析我使用的是阿里巴巴研發的解析

      下載地址:http://download.csdn.net/detail/a985548426/9913248

核心處理:

package com.example.android31_xmlorjson;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import com.alibaba.fastjson.JSON;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public  void getNetXml(View view){
        new MyXmlTask().execute();
    }
    //非同步獲取網路xml
    class MyXmlTask extends AsyncTask{
        @Override
        protected Object doInBackground(Object[] objects) {
            //獲取網路資料
            String path="http://192.168.43.210:8080/student.xml";
            try {
                URL url=new URL(path);
                HttpURLConnection connection= (HttpURLConnection) url.openConnection();
                //設定請求方式(一般提交資料使用POST,獲取資料使用GET)
               connection.setRequestMethod("GET");
                //設定請求時間
               connection.setConnectTimeout(5000);
                //獲取結果碼
                int code=connection.getResponseCode();
                if(200==code){
                 InputStream is=connection.getInputStream();//獲取讀流
                //列印自己的結果
                    //   int len=0;
//                    byte[] buf=new byte[1024];
                    //StringBuffer stringBuffer=new StringBuffer();
//                    while((len=is.read(buf))!=-1){
//                        String s=new String(buf,0,len);
//                        stringBuffer.append(s);
//                    }
                    //Log.i("test",stringBuffer.toString());
                   //解析XML  (我們使用Android特有的pull解析)
                    //例項化解析器
                    XmlPullParser pullParser= Xml.newPullParser();
                    //進行解析  (引數一:資料來源(網路流);引數二:編碼方式)
                    pullParser.setInput(is,"UTF-8");
                    //解析標籤型別
                    int type=pullParser.getEventType();
                     while(type!=XmlPullParser.END_DOCUMENT){ //判斷不是結束標籤
                         switch (type){
                             case XmlPullParser.START_TAG:
                              //獲取開始標籤的名字
                                 String  starTagName=pullParser.getName();
                                 if("student".equals(starTagName)){
                                     //獲取屬性值id的值
                                     String sid=pullParser.getAttributeName(0);
                                     Log.i("test",""+sid);
                                 } else if("sname".equals(starTagName)){
                                     String sname=pullParser.nextText();
                                     Log.i("test",""+sname);
                                 } else if("sage".equals(starTagName)){
                                     String sage=pullParser.nextText();
                                     Log.i("test",""+sage);
                                 }
                                      break;
                             case XmlPullParser.END_TAG:
                                 break;
                         }
                         //細節
                         type=pullParser.next();
                     }
                    //關閉流
                    is.close();
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {
            super.onPostExecute(o);
        }
    }

    public void getNetJSON(View view){
             new MyJsonTask().execute();
    }

    //非同步獲取網路Json
    class MyJsonTask extends AsyncTask{
        @Override
        protected Object doInBackground(Object[] objects) {
         //獲取網路Json
            String  path="http://192.168.43.210:8080/students.json";
            try {
                URL url=new URL(path);
            HttpURLConnection connection= (HttpURLConnection) url.openConnection();
             connection.setRequestMethod("GET");
             connection.setConnectTimeout(5000);
             if(connection.getResponseCode()==200){
                    InputStream is=connection.getInputStream();
                    int len=0;
                  byte[] buf= new byte[1024];
                 StringBuffer sb=new StringBuffer();
                 while ((len=is.read(buf))!=-1){
                  String s=new String(buf,0,len);
                     sb.append(s);
                 }
                 //輸出列印
                 Log.i("test",sb.toString());
               //解析JSON'
            BigObject bigObject=JSON.parseObject(sb.toString(),BigObject.class);
                 int count=bigObject.getCount();
                 Log.i("test",count+"");
               List<Student> stuList=bigObject.getStudents();
                 for (Student sss : stuList) {
                    Log.i("test",sss.getSname()+" "+sss.getSsex());
                 }
             }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Object o) {

            super.onPostExecute(o);
        }
    }



}