android 项目学习随笔五(JSON解析)
1、利用Xutils获取网络数据
/** * 从服务器获取数据 需要权限: <uses-permission * android:name="android.permission.INTERNET"/> */ 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(); } }); }
2、利用gson解析JSON https://github.com/google/gson
创建自定义类(解析JSON返回)
根据JSON的数据结构创建类
import java.util.ArrayList; /** * 新闻中心分类数据 * * gson对象封装原则: * 遇到{}就是一个对象 * 遇到[]就是一个Arraylist * 对象中所有属性命名必须和服务器返回字段完全一致 * */ 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 + "]"; } }
解析JSON
/** * 解析json数据 * * @param result */ protected void processResult(String result) { // gson->json Gson gson = new Gson(); mNewsMenuData = gson.fromJson(result, NewsMenuData.class); System.out.println("解析结果:" + mNewsMenuData); // 获取侧边栏对象 MainActivity mainUI = (MainActivity) mActivity; LeftMenuFragment leftMenuFragment = mainUI.getLeftMenuFragment(); // 将网络数据设置给侧边栏 leftMenuFragment.setData(mNewsMenuData.data); // 初始化4个菜单详情页 mMenuDetailPagers = new ArrayList<BaseMenuDetailPager>(); mMenuDetailPagers.add(new NewsMenuDetailPager(mActivity, mNewsMenuData.data.get(0).children)); mMenuDetailPagers.add(new TopicMenuDetailPager(mActivity)); mMenuDetailPagers.add(new PhotosMenuDetailPager(mActivity)); mMenuDetailPagers.add(new InteractMenuDetailPager(mActivity)); // 菜单详情页-新闻作为初始页面 setCurrentMenuDetailPager(0); }