package com.info.util;
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 com.info.bean.Person;
public class JsonParse {
/**
* 解析Json数据
*
* @param urlPath
* @return mlists
* @throws Exception
*/
public static List<Person> getListPerson(String urlPath) throws Exception {
List<Person> mlists = new ArrayList<Person>();
byte[] data = readParse(urlPath);
JSONArray array = new JSONArray(new String(data));
for (int i = 0; i < array.length(); i++) {
JSONObject item = array.getJSONObject(i);
String name = item.getString("name");
String address = item.getString("address");
int age = item.getInt("age");
mlists.add(new Person(name, address, age));
}
return mlists;
}
/**
* 从指定的url中获取字节数组
*
* @param urlPath
* @return 字节数组
* @throws Exception
*
*Android下的网络编程 & 代理的使用
*
*1. 使用 标准Java接口: 设计的类: java.net.* 基本步骤:
*
*1) 创建 URL 以及 URLConnection / HttpURLConnection 对象 2) 设置连接参数
*3) 连接到服务器 4) 向服务器写数据
*
*5)从服务器读取数据
*
*2. 使用 apache 接口: Apache HttpClient 是一个开源项目,弥补了 java.net.*
*灵活性不足的缺点, 支持客户端的HTTP编程. 使用的类包括: org.apache.http.*
*
*步骤: 1) 创建 HttpClient 以及 GetMethod / PostMethod, HttpRequest
*等对象; 2) 设置连接参数; 3) 执行 HTTP 操作; 4) 处理服务器返回结果.
*/
public static byte[] readParse(String urlPath) throws Exception {
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
URL url = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
InputStream inStream = conn.getInputStream();
while ((len = inStream.read(data)) != -1) {
outStream.write(data, 0, len);
}
inStream.close();
return outStream.toByteArray();
}
}