以下以网址为 urlPath:
http://ikft.house.qq.com/index.php?guid=866500021200250&devua=appkft_1080_1920_XiaomiMI4LTE_1.8.3_Android19&order=0&searchtype=normal&devid=866500021200250&appname=QQHouse&mod=appkft&act=searchhouse&channel=71&page=1&rn=20&cityid=1
举例
从网上请求数据:
try { URL url = new URL(urlPath); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setReadTimeout(5000); conn.setConnectTimeout(5000); if (conn.getResponseCode() == 200) { InputStream is = conn.getInputStream(); Log.e("InputStream", (is == null) + ""); // 将InputStream转成字节数组缓冲流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int len;
while ((len = is.read(b, 0, b.length)) != -1) {
baos.write(b, 0, len);
} // 将流转成字符串
String jsonString = baos.toString(); // 开始解析
lists = JsonParser.parser(jsonString);
}
} catch (Exception e) {
e.printStackTrace();
}在看解析方法之前最好是:
(1)打开百度,搜索BeJson
(2)进入:
在线JSON校验格式化工具(Be JSON),粘贴我的网址去看看JSON数据的结构
以下是解析的方法:
package com.wxw.listviewtest; import android.util.Log; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; public class JsonParser { private static List<FangNu> lists = null; public static List<FangNu> parser(String jsonString){ try { lists = new ArrayList<FangNu>(); // FangNu 实体类 FangNu fangNu = null; JSONObject jsonObject = new JSONObject(jsonString); JSONArray jsonArray = jsonObject.getJSONArray("data"); for(int i=0; i<jsonArray.length(); i++){ fangNu = new FangNu(); JSONObject jsonObject1 = jsonArray.getJSONObject(i); String fcover = (String) jsonObject1.get("fcover"); String fname = (String) jsonObject1.get("fname"); String faddress = (String) jsonObject1.get("faddress"); String price_pre = (String) jsonObject1.get("price_pre"); String fpricedisplaystr = (String) jsonObject1.get("fpricedisplaystr"); Log.e("fcover", fcover); Log.e("fname", fname); Log.e("faddress", faddress); Log.e("price_pre", price_pre); Log.e("fpricedisplaystr", fpricedisplaystr); fangNu.setFcover(fcover); fangNu.setFname(fname); fangNu.setFaddress(faddress); fangNu.setPrice_pre(price_pre); fangNu.setFpricedisplaystr(fpricedisplaystr); lists.add(fangNu); } } catch (JSONException e) { e.printStackTrace(); } return lists; } }