网络爬虫回来json处理数据
网络爬虫返回json处理数据JSON(JavaScript Object Notation) 是一种轻量级的数据交换式。它基于JavaScript(
网络爬虫返回json处理数据
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式。它基于JavaScript(Standard ECMA-262 3rd Edition - December 1999)的一个子集。
URL url;StringBuffer sb = new StringBuffer();String line = null;try {url = new URL("http://api.showji.com/Locating/default.aspx?m=13763089126&output=json&callback=querycallback");HttpURLConnection conn = (HttpURLConnection) url.openConnection();InputStream is = conn.getInputStream();BufferedReader buffer = new BufferedReader(new InputStreamReader(is));while ((line = buffer.readLine()) != null) {sb.append(line);}} catch (MalformedURLException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
此处获取的数据为:
querycallback({"Mobile":"13763******","QueryResult":"True","Province":"广东","City":"湛江","AreaCode":"0759","PostCode":"524000","Corp":"中国移动","Card":"GSM"});
需要截取这个json对象出来。
String js = sb.substring(sb.indexOf("{"), sb.indexOf("}") + 1);
下面函数解析json对象,返回一个Callerloc对象
Callerloc是一个实体类
private Callerloc parse(String json) {Callerloc my = null;if (json == null || json.length() < 1)return null;try {my = new Callerloc();JSONObject jsonobj = new JSONObject(json);my.setMobile(jsonobj.getString("Mobile"));my.setQueryResult(jsonobj.getString("QueryResult"));my.setProvince(jsonobj.getString("Province"));my.setCity(jsonobj.getString("City"));my.setAreaCode(jsonobj.getString("AreaCode"));my.setPostCode(jsonobj.getString("PostCode"));my.setCard(jsonobj.getString("Card"));my.setCorp(jsonobj.getString("Corp"));} catch (JSONException e) {e.printStackTrace();}return my;}
二、解析json数组
json数据为:[{name:"张三:",age:21,sex:"女"},{name:"李斯",age:21,sex:"女"},{name:"王五",age:21,sex:"女"}]
返回list
[java] view plaincopyprint?
- private ArrayList<myjson> parsem(String json) { myjson my = null;
- if (json == null || json.length() < 1)
- return null; try {
- JSONArray jsonary = new JSONArray(json); ArrayList<myjson> objlist = new ArrayList<myjson>();
- for (int i = 0; i < jsonary.length(); i++) { my = new myjson();
- JSONObject jsonobj = jsonary.getJSONObject(i); my.set_name(jsonobj.getString("name"));
- my.set_age(jsonobj.getInt("age")); my.set_sex(jsonobj.getString("sex"));
- objlist.add(my); }
- return objlist; } catch (JSONException e) {
- e.printStackTrace(); }
- return null; }