Android:json及xml解析示例

示例数据

Json

{
    "result": 1,
    "personData": [
        {
            "name": "nate",
            "url": "http://img5.duitang.com/uploads/item/201508/07/20150807093135_G5NMr.png",
            "age": 12,
            "schoolInfo": [
                {
                    "school_name": "北大"
                },
                {
                    "school_name": "清华"
                }
            ]
        },
        {
            "name": "jack",
            "url": "http://v1.qzone.cc/avatar/201404/13/11/12/534a00b62633e072.jpg%21200x200.jpg",
            "age": 23,
            "schoolInfo": [
                {
                    "school_name": "人大"
                },
                {
                    "school_name": "医大"
                }
            ]
        }
    ]
}

Xml



  1
  
    
      nate
      http://img5.duitang.com/uploads/item/201508/07/20150807093135_G5NMr.png
      12
      
        
          北大
        
        
          清华
        
      
    
    
      jack
      http://v1.qzone.cc/avatar/201404/13/11/12/534a00b62633e072.jpg%21200x200.jpg
      23
      
        
          人大
        
        
          医大
        
      
    
  


Android解析json及xml源码

TestJsonXmlParseThread.java

调用WCF服务发布的接口获取测试数据。

import android.content.Context;
import android.widget.ListView;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.params.HttpClientParams;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

public class TestJsonXmlParseThread extends Thread {

    private HttpClient httpClient;

    private Context context;
    private ListView listView;

    public TestJsonXmlParseThread(Context context, ListView listView) {
        httpClient = getHttpClient();
        this.context = context;
        this.listView = listView;
    }

    @Override
    public void run() {
        String url = "http://192.168.0.111:8887/service1/";

        ResultInfo resultInfo = new ResultInfo();

        //解析JSON
        String result = doHttpClientGet(url + "GetJsonInfos");
        try {
            JSONObject jsonObject = new JSONObject(result);
            resultInfo.fromJsonObj(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        //解析XML
//        String result = doHttpClientGet(url + "GetXmlInfos");
//        try {
//            resultInfo = resultInfo.fromXmlObj(result);
//        } catch (XmlPullParserException e) {
//            e.printStackTrace();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

        if (resultInfo != null) {
            final ResultInfoAdapter adapter = new ResultInfoAdapter(context, resultInfo.personData);
            listView.post(new Runnable() {
                @Override
                public void run() {
                    listView.setAdapter(adapter);
                }
            });
        }
    }

    /**
     * 实体对象
     */
    public class ResultInfo {
        public int result;
        public List personData;

        public ResultInfo fromJsonObj(JSONObject jsonObject) throws JSONException {
            if (jsonObject != null) {
                result = jsonObject.getInt("result");
                personData = new ArrayList<>();
                JSONArray jsonArray = jsonObject.getJSONArray("personData");
                if (jsonArray != null) {
                    for (int i=0; i();
                        } else if ("person".equals(name)) {
                            person = new Person();
                        } else if ("name".equals(name)) {
                            person.name = parser.nextText();
                        } else if ("url".equals(name)) {
                            person.url = parser.nextText();
                        } else if ("age".equals(name)) {
                            person.age = Integer.valueOf(parser.nextText());
                        } else if ("schoolInfo".equals(name)) {
                            person.schoolInfo = new ArrayList<>();
                        } else if ("school".equals(name)) {
                            school = new School();
                        } else if ("school_name".equals(name)) {
                            school.school_name = parser.nextText();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("person".equals(name)) {
                            personData.add(person);
                            person = null;
                        } else if ("school".equals(name)) {
                            person.schoolInfo.add(school);
                            school = null;
                        }
                        break;
                }
                event = parser.next();
            }
            return this;
        }
    }

    public class Person {
        public String name;
        public String url;
        public int age;
        public List schoolInfo;

        public Person fromJsonObj(JSONObject jsonObject) throws JSONException {
            if (jsonObject != null) {
                name = jsonObject.getString("name");
                url = jsonObject.getString("url");
                age = jsonObject.getInt("age");
                schoolInfo = new ArrayList<>();
                JSONArray jsonArray = jsonObject.getJSONArray("schoolInfo");
                if (jsonArray != null) {
                    for (int i=0; i

WCF服务部分源码

此处只提供Contract和Service的代码,WCF服务的可配置及参考WCF服务端与使用HttpClient的Android客户端简单示例

IWcfService1.cs

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace Contract
{
    [ServiceContract]
    public interface IWcfService1
    {
        [OperationContract]
        [WebGet(
            UriTemplate = "GetJsonInfos",
            ResponseFormat = WebMessageFormat.Json)]
        ResultInfo GetJsonInfos();

        [OperationContract]
        [WebGet(
            UriTemplate = "GetXmlInfos")]   //默认为XML格式
        ResultInfo GetXmlInfos();
    }

    [DataContract(Name = "resultInfo")]
    public class ResultInfo
    {
        [DataMember(Order = 0, Name = "result")]
        public int Result;

        [DataMember(Order = 1, Name = "personData")]
        public List PersonData;
    }

    [DataContract(Name = "person")]
    public class Person
    {
        [DataMember(Order = 0, Name = "name")]
        public string Name;

        [DataMember(Order = 1, Name = "url")]
        public string URL;

        [DataMember(Order = 2, Name = "age")]
        public int Age;

        [DataMember(Order = 3, Name = "schoolInfo")]
        public List SchoolInfo;
    }

    [DataContract(Name = "school")]
    public class School
    {
        [DataMember(Order = 0, Name = "school_name")]
        public string Name;
    }
}

WcfService1.cs

using Contract;
using System.Collections.Generic;

namespace Service
{
    public class WcfService1 : IWcfService1
    {
        public ResultInfo GetJsonInfos()
        {
            return getResult();
        }

        public ResultInfo GetXmlInfos()
        {
            return getResult();
        }

        private ResultInfo getResult() 
        {
            ResultInfo resultInfo = new ResultInfo();
            resultInfo.Result = 1;
            resultInfo.PersonData = new List();

            List schoolInfo1 = new List();
            schoolInfo1.Add(new School() { Name = "北大" });
            schoolInfo1.Add(new School() { Name = "清华" });
            Person person1 = new Person()
            {
                Name = "nate",
                URL = "http://img5.duitang.com/uploads/item/201508/07/20150807093135_G5NMr.png",
                Age = 12,
                SchoolInfo = schoolInfo1
            };
            resultInfo.PersonData.Add(person1);

            List schoolInfo2 = new List();
            schoolInfo2.Add(new School() { Name = "人大" });
            schoolInfo2.Add(new School() { Name = "医大" });
            Person person2 = new Person()
            {
                Name = "jack",
                URL = "http://v1.qzone.cc/avatar/201404/13/11/12/534a00b62633e072.jpg%21200x200.jpg",
                Age = 23,
                SchoolInfo = schoolInfo2
            };
            resultInfo.PersonData.Add(person2);

            return resultInfo;
        }
    }
}

Android显示解析结果源码

ResultInfoAdapter.java 数据适配器

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

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 ResultInfoAdapter extends BaseAdapter {

    private List list;
    private LayoutInflater layoutInflater;

    public ResultInfoAdapter(Context context, List persons) {
        this.layoutInflater = LayoutInflater.from(context);
        this.list = persons;
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return list.get(i);
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        Holder holder = null;
        if (view == null) {
            view = layoutInflater.inflate(R.layout.parse_item, null);
            holder = new Holder(view);
            view.setTag(holder);
        } else {
            holder = (Holder) view.getTag();
        }

        TestJsonXmlParseThread.Person person = list.get(i);
        holder.txtName.setText("姓名:" + person.name);
        holder.txtAge.setText("年龄:" + person.age);
        holder.txtSchool1.setText("硕士:" + person.schoolInfo.get(0).school_name);
        holder.txtSchool2.setText("本科:" + person.schoolInfo.get(1).school_name);

        //加载在线图片
        new HttpImageThread(person.url, holder.imageView).start();

        return view;
    }

    class Holder {
        private TextView txtName;
        private TextView txtAge;
        private TextView txtSchool1;
        private TextView txtSchool2;
        private ImageView imageView;

        public Holder(View view) {
            txtName = (TextView) view.findViewById(R.id.tv_name);
            txtAge = (TextView) view.findViewById(R.id.tv_age);
            txtSchool1 = (TextView) view.findViewById(R.id.tv_school1);
            txtSchool2 = (TextView) view.findViewById(R.id.tv_school2);
            imageView = (ImageView) view.findViewById(R.id.image);
        }
    }

    class HttpImageThread extends Thread {
        private ImageView imageView;
        private String url;

        public HttpImageThread(String url, ImageView imageView) {
            this.url = url;
            this.imageView = imageView;
        }

        @Override
        public void run() {
            try {
                URL httpUrl = new URL(url);
                HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
                conn.setReadTimeout(5000);
                conn.setRequestMethod("GET");
                InputStream in = conn.getInputStream();
                final Bitmap bitmap = BitmapFactory.decodeStream(in);

                imageView.post(new Runnable() {
                    @Override
                    public void run() {
                        imageView.setImageBitmap(bitmap);
                    }
                });
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

TestJsonXmlActivity.java

import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;

public class TestJsonXmlActivity extends Activity {

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

        ListView listView= (ListView) findViewById(R.id.list_json);
        new TestJsonXmlParseThread(this, listView).start();
    }
}

test_parse.xml




    

parse_item.xml




    

    

        

        

        

    

示例显示结果

Android:json及xml解析示例_第1张图片


参考:

  • http://www.imooc.com/video/8334
  • http://www.imooc.com/video/8335
  • http://blog.csdn.net/love__coder/article/details/6883354

你可能感兴趣的:(Android,WCF)