我们都知道网上有很多第三方解析json的库,比如Gson,但是有时候返回的Json必须要我们手动解析
首先看一下我们要解析Json的结构
解析原理
原理特别简单,就是我们创建bean,然后通过系统自带的api获取Json里面的数据,最后把数据装进我们bean对象,返回bean对象
代码示例
private NewsCenterPagerBean parsedJson2(String json) {
NewsCenterPagerBean bean2 = new NewsCenterPagerBean();
try {
JSONObject object = new JSONObject(json);
JSONObject result = (JSONObject) object.opt("result");
NewsCenterPagerBean.ResultEntity resultEntity = new NewsCenterPagerBean.ResultEntity();
bean2.setResult(resultEntity);
JSONArray data = result.optJSONArray("data");
if (data != null && data.length() > 0) {
List<NewsCenterPagerBean.ResultEntity.DataEntity> dataEntitys = new ArrayList<>();
bean2.getResult().setData(dataEntitys);
//for循环,解析每一条数据
for (int i = 0; i < data.length(); i++) {
JSONObject jsonObject = (JSONObject) data.get(i);
NewsCenterPagerBean.ResultEntity.DataEntity dataEntity = new NewsCenterPagerBean.ResultEntity.DataEntity();
//添加到集合中
dataEntitys.add(dataEntity);
String author_name = jsonObject.optString("author_name");
dataEntity.setAuthor_name(author_name);
String category = jsonObject.optString("category");
dataEntity.setCategory(category);
String date = jsonObject.optString("date");
dataEntity.setDate(date);
String thumbnail_pic_s = jsonObject.optString("thumbnail_pic_s");
dataEntity.setThumbnail_pic_s(thumbnail_pic_s);
String thumbnail_pic_s02 = jsonObject.optString("thumbnail_pic_s02");
dataEntity.setThumbnail_pic_s02(thumbnail_pic_s02);
String thumbnail_pic_s03 = jsonObject.optString("thumbnail_pic_s03");
dataEntity.setThumbnail_pic_s03(thumbnail_pic_s03);
String title = jsonObject.optString("title");
dataEntity.setTitle(title);
String uniquekey = jsonObject.optString("uniquekey");
dataEntity.setUniquekey(uniquekey);
String url = jsonObject.optString("url");
dataEntity.setUrl(url);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return bean2;
}