Android网络通信之解析XML以及解析JSON

来源:互联网 发布:怎么查淘宝等级 编辑:程序博客网 时间:2024/04/28 16:41

XML解析:

    首先在tomcat的webapps里的root中新建一个XML文件,在里面写好所要展示的内容,连上局网

   打开dos命令,输入ipconfig,找到无线局网适配器下的IPv4 地址,复制那串地址,启动tomcat,打开浏览器,

 输入网址:IPv4 地址+tomcat端口号+XML文件,然后回车浏览器中出现XML文件里的内容就对了,那么开始进行下面的代码操作。

我的XML文件如下:

<?xml version="1.0" encoding="UTF-8"?><students><student sid="1"><sname>哈哈哈</sname><ssex>男</ssex></student><student sid="2"><sname>哈哈</sname><ssex>女</ssex></student><student sid="3"><sname>哈</sname><ssex>男</ssex></student></students>


    然后写一个布局:

<?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.android30_parsexml.MainActivity">    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="解析xml"        android:onClick="ParseXML"        /></LinearLayout>


最后再在相应的Activity中解析XML:

package com.example.android30_parsexml;import android.net.Uri;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 android.widget.Toast;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.URI;import java.net.URISyntaxException;import java.net.URL;import java.util.List;import  com.example.android30_parsexml.BigObject;public class MainActivity extends AppCompatActivity {    com.example.android30_parsexml.BigObject object;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);    }    public void ParseXML(View view){    new MyThread().execute();    }    class MyThread extends AsyncTask{        @Override        protected Object doInBackground(Object[] params) {            //获取网络xml            String path="http://193.168.2.168:8080/student.xml";            try {               URL url = new URL(path);                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();           //设置请求方式                httpURLConnection.setRequestMethod("GET");                //设置请求超时时间                httpURLConnection.setConnectTimeout(5000);                //获取结果码(响应码)                int code=httpURLConnection.getResponseCode();                Log.i("test",""+code);                if(code==200){                    //获取数据                    InputStream is= httpURLConnection.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());//                    is.close();                    //开始解析                    XmlPullParser pull=Xml.newPullParser();//生成一个解析器                    pull.setInput(is,"UTF-8");//设置输出编码方式                   int type = pull.getEventType();//解析类型                    //如果还没有结束,就循环遍历                    while(type!=XmlPullParser.END_DOCUMENT){                        switch (type) {                            case XmlPullParser.START_TAG://开始标签                                String name=pull.getName();//开始标签名字                                if("student".equals(name)){                                    String id = pull.getAttributeValue(0);//开始标签的id属性值                                    Log.i("test",id);                                }else if("sname".equals(name)){                                    String sname=pull.nextText();                                    Log.i("test",sname);                                }else if("ssex".equals(name)){                                    String ssex=pull.nextText();                                    Log.i("test",ssex);                                }                            case XmlPullParser.END_TAG://结束标签                                break;                        }                        //细节,跳转到下一个对象                        type=pull.next();                    }                }            } 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);        }    }}


JSON解析:
    首先在tomcat的webapps里的root中新建一个json文件,在里面写好所要展示的内容,连上局网

   打开cmd,输入ipconfig,找到无线局网适配器下的IPv4 地址,复制那串地址,启动tomcat,打开浏览器,

 输入网址:IPv4 地址+tomcat端口号+json文件,然后回车浏览器中出现json文件里的内容就对了,那么开始进行下面的代码操作。

我的JSON文件如下:

{"count":2,students:[{"id":1,"sname":"家具"},{"id":2,"sname":"即可"}]}

然后新建布局:
<?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"    tools:context="com.example.android30_parsexml.Main2Activity">    <Button        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:text="解析json"        android:onClick="ParseJSON"        /></LinearLayout>


由于我的JSON文件中有两个对象,一个集合,所以我分别给对象与集合写两个entity
集合实体类:
package com.example.android30_parsexml;import java.util.List;/** * Created by asus on 2017/7/26. */public class BigObject {    private int count;    private List<Student> students;    public BigObject(int count, List<Student> students) {        this.count = count;        this.students = students;    }    public int getCount() {        return count;    }    public void setCount(int count) {        this.count = count;    }    public List<Student> getStudents() {        return students;    }    public void setStudents(List<Student> students) {        this.students = students;    }    public BigObject() {    }}


对象实体类:
package com.example.android30_parsexml;/** * Created by asus on 2017/7/26. */public class Student {    private int id;    private String sname;    public Student(int id, String sname) {        this.id = id;        this.sname = sname;    }    public Student() {    }    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getSname() {        return sname;    }    public void setSname(String sname) {        this.sname = sname;    }}


最后,再布局所对应的Activity中解析JSON:
package com.example.android30_parsexml;import android.os.AsyncTask;import android.support.v7.app.AppCompatActivity;import android.os.Bundle;import android.util.Log;import android.view.View;import com.alibaba.fastjson.JSON;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 Main2Activity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main2);    }    public void ParseJSON(View view){        new JSONS().execute();    }    class JSONS extends AsyncTask {        @Override        protected Object doInBackground(Object[] params) {            String path="http://193.168.2.168:8080/student.json";            try {                URL url=new URL(path);                HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();                httpURLConnection.setRequestMethod("GET");                httpURLConnection.setConnectTimeout(5000);                InputStream is=httpURLConnection.getInputStream();                int len=0;                byte[] bytes=new byte[1024];                StringBuffer stringBuffer=new StringBuffer();                while((len=is.read(bytes))!=-1){                    String str=new String(bytes,0,len);                    stringBuffer.append(str);                }                //把读流转换成JSON对象               BigObject object = JSON.parseObject(stringBuffer.toString(),BigObject.class);                List<Student> students= object.getStudents();//返回集合                for (Student student : students) {                    Log.i("test",student.getId()+"  "+student.getSname());                }                int a= object.getCount();                Log.i("test",""+a);            } catch (MalformedURLException e) {                e.printStackTrace();            } catch (IOException e) {                e.printStackTrace();            }            return null;        }        @Override        protected void onPostExecute(Object o) {            super.onPostExecute(o);        }    }}




我在运行解析JSON的Activity时,报了一个找不到集合实体类的错,原因是因为我的对象实体类没有写空的构造方法。因此,在两个实体类当中,都要加上无参的构造方法,不然就会报这个错。