{
"data": [
{
"children": [
{
"id": 10007,
"title": "北京",
"type": 1,
"url": "/10007/list_1.json"
},
{
"id": 10006,
"title": "中国",
"type": 1,
"url": "/10006/list_1.json"
},
{
"id": 10008,
"title": "国际",
"type": 1,
"url": "/10008/list_1.json"
},
{
"id": 10010,
"title": "体育",
"type": 1,
"url": "/10010/list_1.json"
},
{
"id": 10091,
"title": "生活",
"type": 1,
"url": "/10091/list_1.json"
},
{
"id": 10012,
"title": "旅游",
"type": 1,
"url": "/10012/list_1.json"
},
{
"id": 10095,
"title": "科技",
"type": 1,
"url": "/10095/list_1.json"
},
{
"id": 10009,
"title": "军事",
"type": 1,
"url": "/10009/list_1.json"
},
{
"id": 10093,
"title": "时尚",
"type": 1,
"url": "/10093/list_1.json"
},
{
"id": 10011,
"title": "财经",
"type": 1,
"url": "/10011/list_1.json"
},
{
"id": 10094,
"title": "育儿",
"type": 1,
"url": "/10094/list_1.json"
},
{
"id": 10105,
"title": "汽车",
"type": 1,
"url": "/10105/list_1.json"
}
],
"id": 10000,
"title": "新闻",
"type": 1
},
{
"id": 10002,
"title": "专题",
"type": 10,
"url": "/10006/list_1.json",
"url1": "/10007/list1_1.json"
},
{
"id": 10003,
"title": "组图",
"type": 2,
"url": "/10008/list_1.json"
},
{
"dayurl": "",
"excurl": "",
"id": 10004,
"title": "互动",
"type": 3,
"weekurl": ""
}
],
"extend": [
10007,
10006,
10008,
10014,
10012,
10091,
10009,
10010,
10095
],
"retcode": 200
}
JSON数据如上 现在用Gson对上面的复杂数据进行解析 先建立JAVABEAN对象 来封装:
gson对象封装原则:
* 遇到{}就是一个对象
* 遇到[]就是一个Arraylist
* 对象中所有属性命名必须和服务器返回字段完全一致
所以上面的been应该这么写:
public class NewsMenuData { public int retcode;
public ArrayList<String> extend;
public ArrayList<NewsData> data; public class NewsData {
public String id;
public String title;
public int type;
public ArrayList<NewsTabData> children; @Override
public String toString() {
return "NewsData [title=" + title + ", children=" + children + "]";
}
} // 页签信息封装
public class NewsTabData {
public String id;
public String title;
public String url;
public int type; @Override
public String toString() {
return "NewsTabData [title=" + title + "]";
}
} @Override
public String toString() {
return "NewsMenuData [data=" + data + "]";
}
}
请求数据:用的xutils框架.
private void getDataFromServer() {
HttpUtils utils = new HttpUtils();
utils.send(HttpMethod.GET, Constants.CATEGORIES_URL,
new RequestCallBack<String>() { @Override
public void onSuccess(ResponseInfo<String> responseInfo) {
// 请求成功
String result = responseInfo.result;// 获取json字符串
// System.out.println("result:" + result);
processResult(result);
// 写缓存
CacheUtils.setCache(Constants.CATEGORIES_URL, result,
mActivity);
} @Override
public void onFailure(HttpException error, String msg) {
// 请求失败
error.printStackTrace();
Toast.makeText(mActivity, msg, Toast.LENGTH_SHORT)
.show();
}
});
}
Gson解析的方法
protected void processResult(String result) {
// gson->json
Gson gson = new Gson();
mNewsMenuData = gson.fromJson(result, NewsMenuData.class);
System.out.println("解析结果:" + mNewsMenuData);
}