xml與json

package com.itheima.xml;

import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;

public class MainActivity extends Activity {

	private PersonService service;

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

		service = new PersonService();
	}
	
	public void getJson(View v) {		// AsyncHttpClient改造
		new Thread() {
			public void run() {
				try {
					List<Person> list = service.getJsonPersons();
					for (Person p : list) {
						System.out.println(p);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

	public void getXml(View v) throws Exception {
		new Thread() {
			public void run() {
				try {
					List<Person> list = service.getXmlPersons();
					for (Person p : list) {
						System.out.println(p);
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}

}


package com.itheima.xml;

public class Person {
	private Long id;
	private String name;
	private Integer age;

	public Person() {
		super();
	}

	public Person(Long id, String name, Integer age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "Person [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

}

package com.itheima.xml;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;

import android.util.Xml;

public class PersonService {

	public List<Person> getXmlPersons() throws Exception {
		URL url = new URL("http://192.168.1.228:8080/05.Web/persons.xml");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		
		int code = conn.getResponseCode();
		if (code == 200) {
			InputStream in = conn.getInputStream();
			return parseXml(in);
		}
		
		throw new RuntimeException("網絡出錯: " + code);
	}

	private List<Person> parseXml(InputStream in) throws Exception {
		List<Person> list = new ArrayList<Person>();
		Person p = null;
		
		XmlPullParser parser = Xml.newPullParser();
		parser.setInput(in, "UTF-8");
		for (int type = parser.getEventType(); type != XmlPullParser.END_DOCUMENT; type = parser.next()) {
			if (type == XmlPullParser.START_TAG) {
				if ("person".equals(parser.getName())) {
					p = new Person();
					String id = parser.getAttributeValue(0);
					p.setId(Long.parseLong(id));
					list.add(p);
				} else if ("name".equals(parser.getName())) {
					String name = parser.nextText();
					p.setName(name);
				} else if ("age".equals(parser.getName())) {
					String age = parser.nextText();
					p.setAge(Integer.parseInt(age));
				}
			}
		}
		
		return list;
	}

	public List<Person> getJsonPersons() throws Exception {
		URL url = new URL("http://192.168.1.228:8080/05.Web/persons.js");
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setConnectTimeout(5000);
		
		int code = conn.getResponseCode();
		if (code == 200) {
			InputStream in = conn.getInputStream();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			byte[] buffer = new byte[8192];
			int length;
			while((length = in.read(buffer)) != -1) 			// 從網絡讀取數據
				out.write(buffer, 0, length);					// 把數據寫到內存
			in.close();
			out.close();
			
			byte[] data = out.toByteArray();
			String json = new String(data);
			return parseJson(json);
		}
		return null;
	}

	private List<Person> parseJson(String json) throws Exception {
		List<Person> list = new ArrayList<Person>();
		JSONArray arr = new JSONArray(json);		// 把字符串封裝成JSON數組
		for (int i = 0; i < arr.length(); i++) {	// 遍歷JSON數組
			JSONObject obj = arr.getJSONObject(i);	// 從JSON數組中獲取每個JSON對象
			Person p = new Person();
			p.setId(obj.getLong("id"));				// 從JSON對象中獲取id屬性
			p.setName(obj.getString("name"));
			p.setAge(obj.getInt("age"));
			list.add(p);
		}
		return list;
	}

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章