示例数据
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
<?xml version="1.0"?>
<resultInfo xmlns="http://schemas.datacontract.org/2004/07/Contract" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<result>1</result>
<personData>
<person>
<name>nate</name>
<url>http://img5.duitang.com/uploads/item/201508/07/20150807093135_G5NMr.png</url>
<age>12</age>
<schoolInfo>
<school>
<school_name>北大</school_name>
</school>
<school>
<school_name>清华</school_name>
</school>
</schoolInfo>
</person>
<person>
<name>jack</name>
<url>http://v1.qzone.cc/avatar/201404/13/11/12/534a00b62633e072.jpg%21200x200.jpg</url>
<age>23</age>
<schoolInfo>
<school>
<school_name>人大</school_name>
</school>
<school>
<school_name>医大</school_name>
</school>
</schoolInfo>
</person>
</personData>
</resultInfo>
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<Person> 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<jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
personData.add(new Person().fromJsonObj(object));
}
}
}
return this;
}
public ResultInfo fromXmlObj(String xmlString) throws XmlPullParserException, IOException {
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
XmlPullParser parser = factory.newPullParser();
parser.setInput(new StringReader(xmlString));
int event = parser.getEventType();
//临时变量
String name = "";
Person person = null;
School school = null;
//解析xml
while (event != XmlPullParser.END_DOCUMENT) {
name = parser.getName();
switch (event) {
case XmlPullParser.START_TAG:
if ("result".equals(name)) {
result = Integer.valueOf(parser.nextText());
} else if ("personData".equals(name)) {
personData = new ArrayList<>();
} 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<School> 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<jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
schoolInfo.add(new School().fromJsonObj(object));
}
}
}
return this;
}
}
public class School {
public String school_name;
public School fromJsonObj(JSONObject jsonObject) throws JSONException {
if (jsonObject != null) {
school_name = jsonObject.getString("school_name");
}
return this;
}
}
private String doHttpClientGet(String url) {
String result = "";
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
result = EntityUtils.toString(httpResponse.getEntity());
}
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
private HttpClient getHttpClient() {
HttpParams httpParams = new BasicHttpParams();
//设置连接超时、Socket超时、Socket缓存大小
HttpConnectionParams.setConnectionTimeout(httpParams, 20 * 1000);
HttpConnectionParams.setSoTimeout(httpParams, 20 * 1000);
HttpConnectionParams.setSocketBufferSize(httpParams, 8192);
//设置重定向,缺省为true
HttpClientParams.setRedirecting(httpParams, true);
HttpClient httpClient = new DefaultHttpClient(httpParams);
return httpClient;
}
}
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<Person> 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<School> 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<Person>();
List<School> schoolInfo1 = new List<School>();
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<School> schoolInfo2 = new List<School>();
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<TestJsonXmlParseThread.Person> list;
private LayoutInflater layoutInflater;
public ResultInfoAdapter(Context context, List<TestJsonXmlParseThread.Person> 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
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/list"></ListView>
</LinearLayout>
parse_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="3"
android:layout_marginTop="5dp"
android:padding="10dp">
<ImageView
android:id="@+id/image"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_weight="1"
android:src="@mipmap/ic_launcher"/>
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:weightSum="3"
android:orientation="vertical"
android:layout_marginLeft="20dp">
<TextView
android:layout_width="match_parent"
android:layout_height="40dp"
android:id="@+id/tv_name"
android:text="name"
android:layout_weight="1"
android:textSize="20sp"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="35dp"
android:id="@+id/tv_age"
android:text="age"
android:layout_weight="1"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="35dp"
android:id="@+id/tv_school1"
android:text="school1"
android:layout_weight="1"
android:textSize="18sp"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="35dp"
android:id="@+id/tv_school2"
android:text="school2"
android:layout_weight="1"
android:textSize="18sp"
android:textStyle="bold"/>
</LinearLayout>
示例显示结果
参考: