您的位置:首页 > 移动开发 > Android开发

android解析json字符串

2012-07-19 17:04 323 查看
目标json字符串:{"error":"","data":[{"fid":"1","forums": [{"fid":"1","name":"Discuz!","threads":"0","posts":"0","todayposts":"0","type":"group","lastpost":""}, {"fid":"2","name":"默认版块","threads":"1","posts":"1","todayposts":"0","type":"forum","lastpost":"07-09"}]},
{"fid":"3","forums":[{"fid":"3","name":"游戏","threads":"0","posts":"0","todayposts":"0","type":"group","lastpost":""}, {"fid":"8","name":"家庭机","threads":"0","posts":"0","todayposts":"0","type":"forum","lastpost":""}, {"fid":"7","name":"网络","threads":"0","posts":"0","todayposts":"0","type":"forum","lastpost":""},
{"fid":"6","name":"单机","threads":"0","posts":"0","todayposts":"0","type":"forum","lastpost":""}]}, {"fid":"4","forums":[{"fid":"4","name":"体育","threads":"0","posts":"0","todayposts":"0","type":"group","lastpost":""}, {"fid":"10","name":"足球","threads":"0","posts":"0","todayposts":"0","type":"forum","lastpost":""},
{"fid":"9","name":"篮球","threads":"32","posts":"42","todayposts":"1","type":"forum","lastpost":"13 分钟前"}]},{"fid":"5","forums":[{"fid":"5","name":"水区","threads":"0","posts":"0","todayposts":"0","type":"group","lastpost":""}, {"fid":"11","name":"水区","threads":"0","posts":"0","todayposts":"0","type":"forum","lastpost":""}]}]}

这是相对负责的json字符串:对象中嵌套数组,数组中有json对象,接下来又是json数组,呵呵

看解析:indexList=new ArrayList<IndexObj>();

InputStream stream=null;

try {

//通过url读出json字符串

URL url=new URL(str);

HttpURLConnection conn=(HttpURLConnection) url.openConnection();

stream=conn.getInputStream();

byte[] buffer = new byte[1024];

ByteArrayOutputStream baos = new ByteArrayOutputStream();

int len = 0;

while ((len = stream.read(buffer)) != -1) {

EncodingUtils.getString(buffer, "utf-8");

baos.write(buffer, 0, len);

}

str=baos.toString();

} catch (MalformedURLException e1) {

e1.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

try {

//字符串化成json对象

JSONObject jsonObject=new JSONObject(str);

//对象得到json数组

JSONArray indexArray=jsonObject.getJSONArray("data");

int indexLength=indexArray.length();

for (int i = 0; i < indexLength; i++) {

//json数组化成json对象

JSONObject indexobj1=(JSONObject) indexArray.get(i);

JSONArray array=indexobj1.getJSONArray("forums");

for (int j = 0; j < array.length(); j++) {

JSONObject indexobj=array.getJSONObject(j);

IndexObj index=new IndexObj();

index.setFid(indexobj.getInt("fid"));

index.setName(indexobj.getString("name"));

index.setThreads(indexobj.getInt("threads"));

index.setPosts(indexobj.getInt("posts"));

index.setTodayposts(indexobj.getInt("todayposts"));

index.setType(indexobj.getString("type"));

index.setLastpost(indexobj.getString("lastpost"));

indexList.add(index);

Log.e("index","--->"+index.getFid()+" name-->"+index.getName());

}

}

} catch (JSONException e) {

Log.e("getIndexJson",e.getMessage());

e.printStackTrace();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: