1. 解析 [{\"id\":1,\"name\":\"kang\"},{\"id\":2,\"name\":\"zhang\"}] 此种格式的Json数据
package com.sunplus.app.util;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONObject;
/**
* @author kanglb (http://blog.csdn.net/nmsoftklb) created :2013-4-17
*
*/
public class ConnInternet {
public static String getInputStream() {
String path = "http://172.20.223.143:8080/run/json/demo.jsp";
String temp = null;
try {
URL url = new URL(path); // 实例化一个URL对象
HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 使用url的openConnection()方法打开一个链接
conn.setConnectTimeout(1000 * 5);// 设置连接超时时间
conn.setRequestMethod("GET"); // 设置请求方式
if (conn.getResponseCode() == 200) {
byte[] buffer = new byte[1024];
int len = conn.getInputStream().read(buffer);
if (len > 0) {
temp = new String(buffer, 0, len);
List<Map<String, Object>> all = parseJson(temp);
for (Map<String, Object> list : all) {
android.util.Log.d("mark", "id=" + list.get("id") + "name=" + list.get("name")); //测试输出
}
return temp;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//
private List<Map<String, Object>> parseJson(String data) {
List<Map<String, Object>> all = new ArrayList<Map<String, Object>>();
try {
JSONArray array = new JSONArray(data);
for (int i = 0; i < array.length(); i++) {
Map<String, Object> map = new HashMap<String, Object>();
JSONObject item = array.getJSONObject(i);
map.put("id", item.getInt("id"));
map.put("name", item.getString("name"));
all.add(map);
}
} catch (Exception e) {
e.printStackTrace();
}
return all;
}
}
android 解析Json格式的数据(一)
最新推荐文章于 2024-09-11 08:40:34 发布