Android笔记----对服务器XML以及JSON数据的简单解析

  1. 服务器搭建
    Apache官网最新版Apache HTTP Server 2.4安装方法已经不是傻瓜式的下一步,需要解压完成后进行手动配置相关路径和端口信息,昨天由于端口冲突问题折腾了挺长时间终于搞定了.
    最终设置本地ip(localhost)+端口号作为服务器主站,相对应的数据文件也是放在这里面Android笔记----对服务器XML以及JSON数据的简单解析_第1张图片
    丢入test.xml以及testjson.json作为测试.
    Android笔记----对服务器XML以及JSON数据的简单解析_第2张图片

  • 简单思路摘要:
    1. XML
      通过HttpClient获取网址中xml文件的数据,再Pull方式解析服务器返回的数据.
    2. JSON
      JSON的解析相对清晰,直接把数据返回到JSONArray对象, 并对改对象每个元素的成员调用getString()取出.

But Talk is cheap, show me the code…

新建AndroidProject
1.先在AndroidManifest声明权限

2.布局相对简单,只是个按钮监听实现:
在onClick里面回调即可

//解析xml
sendRequestWithHttpURLConnection_xml();
//JSONArray 解析json
sendRequestWithHttpURLConnection_json();
//          GSON解析JSON
sendRequestWithHttpURLConnection_GSON();

具体函数
XML
网站下的test.xml内容为:

<apps>
    <app>
        <id>626995617id>
        <name>Dhname>
        <version>1.0version>
    app>

    <app>
        <id>2id>
        <name>kbname>
        <version>2.0version>
    app>

    <app>
        <id>3id>
        <name>ljname>
        <version>3.0version>
    app>
apps>

解析的时候是按每个结点(app)进行解析的 ,类似于文件读取操作,遇到结点就判断是否到达文件尾,如果否,则next(app)

public void sendRequestWithHttpURLConnection_xml() {
        new Thread(new Runnable() {         
            @Override
            public void run() {
                try{
                    Log.d(TAG,"run");
                    HttpClient httpClient = new DefaultHttpClient();
                    //指定地址
                    HttpGet httpGet = new HttpGet("http://10.15.27.157:8080/test.xml");
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        Log.d(TAG,"success");
                        //请求响应成功
                        HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity,"utf-8");                     
                        parseXMLWithPull(response);
                    }
                }catch(Exception e){
                    e.printStackTrace();
                }
            }           
        }).start();
    }

    private void parseXMLWithPull(String xmlData) {
        try {
            Log.d(TAG,"parseXMLWithPull");
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            XmlPullParser xmlPullParser = factory.newPullParser();
            xmlPullParser.setInput(new StringReader(xmlData));
            int eventType = xmlPullParser.getEventType();
            String id = "";
            String name = "";
            String version = "";
            while (eventType != XmlPullParser.END_DOCUMENT) {
                //xml未到文件末尾
                String nodeNameString = xmlPullParser.getName();
                switch (eventType) {
                case XmlPullParser.START_TAG:{
                    if ("id".equals(nodeNameString)) {
                        id = xmlPullParser.nextText();
                    }else if ("name".equals(nodeNameString)){
                        name = xmlPullParser.nextText();
                    }else if ("version".equals(nodeNameString)){
                        version = xmlPullParser.nextText();
                    }                   
                    break;
                }

                case XmlPullParser.END_TAG:{
                    if ("app".equals(nodeNameString)) {
                        Log.d(TAG,"id is "+id);
                        Log.d(TAG,"name is "+name);
                        Log.d(TAG,"Version is "+version);
                    }
                    break;
                }
                default :
                    break;
                }
                eventType = xmlPullParser.next();
            }           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }    

解析结果:
Android笔记----对服务器XML以及JSON数据的简单解析_第3张图片

JSON
test_json.json内容为:

[
    { "id":"5","version":"5.5","name":"AG" },
    { "id":"6","version":"6.0","name":"Six" },
    { "id":"7","version":"7.0","name":"Seven" }
]

JSON格式数据体积小,但是.json可读性差,可以借助辅助工具

http://www.bejson.com/ 在线解析
Android笔记----对服务器XML以及JSON数据的简单解析_第4张图片

这样比较清晰
Android笔记----对服务器XML以及JSON数据的简单解析_第5张图片
JSON的解析相对清晰,直接把数据返回到JSONArray对象, 并循环遍历JSONArray对象,对该对象每个元素的成员(id,name,version)调用getString()取出.

private void sendRequestWithHttpURLConnection_json() {
        new Thread(new Runnable() {         
            @Override
            public void run() {
                try{
                    Log.d(TAG,"run");
                    HttpClient httpClient = new DefaultHttpClient();
                    //指定地址
                    HttpGet httpGet = new HttpGet("http://10.15.27.157:8080/test_json.json");
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        Log.d(TAG,"success");
                        //请求响应成功
                        HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity,"utf-8");                     
                        parseJSONWithJSONObject(response);
                    }
                }catch(Exception 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.d(TAG,"id is "+id);
                Log.d(TAG,"name is "+name);
                Log.d(TAG,"Version is "+version);

            }           
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

解析结果我们通过logcat输出:
Android笔记----对服务器XML以及JSON数据的简单解析_第6张图片

  • GSON解析JSON,相对更加方便
    Eclipse 平台,
    下载GSON的压缩包 解压得到gson-2.2.4

  • Step 1 在项目的lib导入gson-2.2.4
    Android笔记----对服务器XML以及JSON数据的简单解析_第7张图片

  • Step 2 新建类 Data_GSON

//    GSON解析JSON
    private void sendRequestWithHttpURLConnection_GSON() {
        new Thread(new Runnable() {         
            @Override
            public void run() {
                try{
                    Log.d(TAG,"GSON解析");
                    HttpClient httpClient = new DefaultHttpClient();
                    //指定地址
                    HttpGet httpGet = new HttpGet("http://10.15.27.157:8080/test_json.json");
                    HttpResponse httpResponse = httpClient.execute(httpGet);
                    if (httpResponse.getStatusLine().getStatusCode() == 200) {
                        Log.d(TAG,"success");
                        //请求响应成功
                        HttpEntity entity = httpResponse.getEntity();
                        String response = EntityUtils.toString(entity,"utf-8");                     
                        parseJSONWithG(response);
                    }                   
                }catch(Exception e){
                    e.printStackTrace();
                }
            }                   
        }).start();
    }

    private void parseJSONWithG(String jsonData) {
        Gson gson = new Gson();
        List<Data_GSON>appList = 
                gson.fromJson(jsonData, new TypeToken<List<Data_GSON>>(){}.getType());
        for (Data_GSON data_GSON : appList) {
            Log.d(TAG,"id is "+ data_GSON.getId());
            Log.d(TAG,"name is "+ data_GSON.getName());
            Log.d(TAG,"Version is "+ data_GSON.getVersion());
        }
    }

以上方法同样可以成功解析,代码和上面的JSONArray方法大同小异,关键地方在于
此处解析JSON数据只需要通过自定义的类Data_GSON来进行识别

其实GSON库是将JSON字符串映射成对象,然后匹配相应的成员变量进行获取.

//对JSON数组的统一 
Gson gson = new Gson();

        ListappList = 
                gson.fromJson(jsonData, new TypeToken<List>(){}.getType());

程序来源<第一行代码>

你可能感兴趣的:(Android)