赞
踩
- {
- "paramz": {
- "feeds": [
- {
- "id": 299076,
- "oid": 288340,
- "category": "article",
- "data": {
- "subject": "荔枝新闻3.0:不止是阅读",
- "summary": "江苏广电旗下资讯类手机应用“荔枝新闻”于近期推出全新升级换代的3.0版。",
- "cover": "/Attachs/Article/288340/3e8e2c397c70469f8845fad73aa38165_padmini.JPG",
- "pic": "",
- "format": "txt",
- "changed": "2015-09-22 16:01:41"
- }
- }
- ],
- "PageIndex": 1,
- "PageSize": 20,
- "TotalCount": 53521,
- "TotalPage": 2677
- }
- }
其实JSON数据就是一段字符串而已,只不过有不同意义的分隔符将其分割开来而已,我们看上面的符号,里面有[] ,{}等符号,其中
1 []中括号代表的是一个数组;
2 {}大括号代表的是一个对象
3 双引号“”表示的是属性值
4 冒号:代表的是前后之间的关系,冒号前面是属性的名称,后面是属性的值,这个值可以是基本数据类型,也可以是引用数据类型。
JSONObject系统自带的解析方式解析,我们先来JSONObject(系统自带的类)类中的方法:
- public class JsonUtils {
-
- /**
- * 根据json数据解析返回一个List<HashMap<String, Object>>集合
- * @param json json数据
- * @return
- */
- public static List<HashMap<String, Object>> getJsonList(String json) {
- List<HashMap<String, Object>> dataList;
- dataList = new ArrayList<>();
- try {
- JSONObject rootObject = new JSONObject(json);
- JSONObject paramzObject = rootObject.getJSONObject("paramz");
- JSONArray feedsArray = paramzObject.getJSONArray("feeds");
- for (int i = 0; i < feedsArray.length(); i++) {
- JSONObject sonObject = feedsArray.getJSONObject(i);
- JSONObject dataObject = sonObject.getJSONObject("data");
- String subjectStr = dataObject.getString("subject");
- String summaryStr = dataObject.getString("summary");
- String coverStr = dataObject.getString("cover");
- HashMap<String, Object> map = new HashMap<>();
- map.put("subject", subjectStr);
- map.put("summary", summaryStr);
- map.put("cover", coverStr);
- dataList.add(map);
- }
- return dataList;
- } catch (JSONException e) {
- e.printStackTrace();
- }
- return null;
- }
- }
相信很简单一看就懂了吧,此方法写起来主要是比较费时间罢了,无非就是几个方法不停的调用而已,所以显得特别的费时费力,下面我又写了一个解析的方法,方法中会有一些冗余的代码,是为了更加深刻理解JSON解析而写的,实际中可以删掉,也用了一行GSON解析,GSON解析下面会见讲到:
其中DataModel对象我是将data对象使用GsonFormat插件工具生成的,使用方式可以自行搜索
- public class DataModel {
-
- /**
- * subject : "荔枝新闻3.0:不止是阅读"
- * summary : "江苏广电旗下资讯类手机应用“荔枝新闻”于近期推出全新升级换代的3.0版。"
- * cover : "/Attachs/Article/288340/3e8e2c397c70469f8845fad73aa38165_padmini.JPG"
- * pic :
- * format : video
- * changed : 2015-11-07 14:35:22
- */
-
- public String subject;
- public String summary;
- public String cover;
- public String pic;
- public String format;
- public String changed;
-
- @Override
- public String toString() {
- return "DataModel{" +
- "subject='" + subject + '\'' +
- ", summary='" + summary + '\'' +
- ", cover='" + cover + '\'' +
- ", pic='" + pic + '\'' +
- ", format='" + format + '\'' +
- ", changed='" + changed + '\'' +
- '}';
- }
- }
- /**
- * 根据json对象获取List<DataModel>集合
- * @param json 数据
- * @return
- */
- public static List<DataModel> getGsonList(String json) {
- List<DataModel> dataList;
- try {
- JSONObject rootObject = new JSONObject(json);
- JSONObject paramzObject = rootObject.getJSONObject("paramz");
-
- /**
- * JSONArray的构造方法获取JSONArray对象
- */
- JSONArray jsonArray = new JSONArray(paramzObject.getString("feeds"));
- Log.i(TAG, "jsonarray.length():"+jsonArray.length());
-
- /**
- * 获取JSONObject对象的属性关键字
- */
- Iterator<String> iterators = paramzObject.keys();
- while (iterators.hasNext()) {
- Log.i(TAG, "iterators: " + iterators.next());
- }
- JSONArray feeds = paramzObject.getJSONArray("feeds");
- dataList = new ArrayList<>();
- for (int i = 0; i < feeds.length(); i++) {
- JSONObject jsonObject = feeds.getJSONObject(i);
- DataModel model = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<DataModel>() {
- }.getType());
- Log.i(TAG, "DataModel: " + model.toString());
- dataList.add(model);
- }
- return dataList;
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return null;
- }
- /**
- * 根据json对象获取List<DataModel>集合
- * @param json 数据
- * @return
- */
- public static List<DataModel> getGsonList(String json) {
- List<DataModel> dataList;
- try {
- JSONObject rootObject = new JSONObject(json);
- JSONObject paramzObject = rootObject.getJSONObject("paramz");
-
- /**
- * JSONArray的构造方法获取JSONArray对象
- */
- JSONArray jsonArray = new JSONArray(paramzObject.getString("feeds"));
- Log.i(TAG, "jsonarray.length():"+jsonArray.length());
-
- /**
- * 获取JSONObject对象的属性关键字
- */
- Iterator<String> iterators = paramzObject.keys();
- while (iterators.hasNext()) {
- Log.i(TAG, "iterators: " + iterators.next());
- }
- JSONArray feeds = paramzObject.getJSONArray("feeds");
- dataList = new ArrayList<>();
- for (int i = 0; i < feeds.length(); i++) {
- JSONObject jsonObject = feeds.getJSONObject(i);
- DataModel model = new Gson().fromJson(jsonObject.getString("data"), new TypeToken<DataModel>() {
- }.getType());
- Log.i(TAG, "DataModel: " + model.toString());
- dataList.add(model);
- }
- return dataList;
- } catch (JSONException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- return null;
- }
简单总结一下上面的解析吧:
1 对于JSONObject对象来说,想要得到一个JSONObject对象通常可以通过
(a):构造方式:JSONObject(String json)-> JSONObject rootObject = new JSONObject(json);
(b):JSONObject getJSONObject(String name){}-> JSONObject paramzObject = rootObject.getJSONObject(“paramz”);
2 对于JSONArray对象来说,想要得到一个JSONArray对象通常可以通过
(a):构造方式:JSONArray(String json)->JSONArray jsonArray = new JSONArray(paramzObject.getString(“feeds”));
(b):JSONObject getJSONObject(String name){}-> JSONArray feeds = paramzObject.getJSONArray(“feeds”);
我们如果懂得了上面的手动解析方式的话,那么对于Gson解析而言,就太简单了,下面我们就开始解析下面一段JSON数据:
- {
- "homeadlist": [
- {
- "id": 1,
- "imgurl": "/img/homead/a73b3f1d-0f14-429d-9d0f-70643fb0f0eb.jpg",
- "jumpflag": 0,
- "jumpurl": "",
- "posflag": 1,
- "remark": "1111",
- "cityid": 1
- },
- {
- "id": 12,
- "imgurl": "/img/homead/eb442fbf-49db-4ba6-a102-d781505f426d.jpg",
- "jumpflag": 0,
- "jumpurl": "",
- "posflag": 2,
- "remark": "",
- "cityid": 1
- },
- {
- "id": 14,
- "imgurl": "/img/homead/68109460-635d-4c5c-8be8-64d7c7889d18.jpg",
- "jumpflag": 0,
- "jumpurl": "http://shiranlife.kuaizhan.com/",
- "posflag": 4,
- "remark": "",
- "cityid": 1
- }
- ]
- }
首先我们使用GsonFormat工具生成一个类HomeadListModel:
- public class HomeadListModel {
-
- /**
- * code : 1
- * data : {"homeadlist":[{"id":1,"imgurl":"/img/homead/a73b3f1d-0f14-429d-9d0f-70643fb0f0eb.jpg","jumpflag":0,"jumpurl":"","posflag":1,"remark":"1111","cityid":1},{"id":12,"imgurl":"/img/homead/eb442fbf-49db-4ba6-a102-d781505f426d.jpg","jumpflag":0,"jumpurl":"","posflag":2,"remark":"","cityid":1},{"id":14,"imgurl":"/img/homead/68109460-635d-4c5c-8be8-64d7c7889d18.jpg","jumpflag":0,"jumpurl":"http://shiranlife.kuaizhan.com/","posflag":4,"remark":"","cityid":1}]}
- */
-
- public int code;
- public DataBean data;
-
- public static class DataBean {
- public List<HomeadlistBean> homeadlist;
-
- public static class HomeadlistBean {
- public int id;
- public String imgurl;
- public int jumpflag;
- public String jumpurl;
- public int posflag;
- public String remark;
- public int cityid;
- }
- }
- }
-
我们使用OKHttpClient,代码如下
- OkHttpClient.Builder builder = new OkHttpClient.Builder();
-
- Request request = new Request.Builder()
- .url(url)
- .get()
- .build();
-
- builder.build().newCall(request).enqueue(new Callback() {
- @Override
- public void onFailure(Call call, IOException e) {
-
- }
-
- @Override
- public void onResponse(Call call, Response response) throws IOException {
- Gson gson = new Gson();
- /**
- * java.lang.IllegalStateException: closed
- * 因为OkHttp请求回调中response.body().string()只能有效调用一次
- *
- */
-
- String string = response.body().string();
- Log.i("aaa", "response: " + string);
- /**
- * 重新构建一个response 因为response.body().string()调用一次之后流就断掉了,只能有效调用一次
- */
- MediaType mediaType = response.body().contentType();
- Response response1 = response.newBuilder().body(ResponseBody.create(mediaType, string)).build();
- String string1 = response1.body().string();
- Log.i("aaa", "response1: " + string1);
- /**
- * 将json数据转换为对象
- */
- HomeadListModel model = gson.fromJson(string1, HomeadListModel.class);
- //HomeadListModel model2 = gson.fromJson(string1, new TypeToken<HomeadListModel>() {
- }.getType());
- /**
- * 将对象转换为json数据
- */
- String jsonString = gson.toJson(model);
- Log.i("aaa", "onResponse2: " + jsonString);
-
- for (HomeadListModel.DataBean.HomeadlistBean data : model.data.homeadlist) {
- mData.add(imageUrl + data.imgurl);
- }
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mAdapter.notifyDataSetChanged();
- }
- });
- }
- });
我们想要将一个json数据转换为对象的话需要使用fromJson(String json, Class classOfT) /fromJson(String json, Type typeOfT),当我们需要将对象转换为String的时候根据String toJson(Object src)方法即可。这里需要注意一点,如果response.body().string()调用大于一次的话,就会报错java.lang.IllegalStateException: closed,因为response.body().string()调用一次之后流就断掉了,需要重新构建一个response;
这个解析和Gson解析差不多,也是一行就搞定了,也是对上面的Gson数据进行解析,想要将json数据解析成对象需要使用 parseObject()方法,参数可以传Class,也可以传Type;当需要通过对象得到String字符串时候使用String json1 = JSONObject.toJSONString(model)即可,下面贴上代码:
- OkHttpClient.Builder builder = new OkHttpClient.Builder();
- Request request = new Request.Builder()
- .url(url)
- .get()
- .build();
- builder.build().newCall(request).enqueue(new Callback() {
- @Override
- public void onFailure(Call call, IOException e) {
-
- }
-
- @Override
- public void onResponse(Call call, Response response) throws IOException {
-
- String json = response.body().string();
- /**
- * 根据json数据获取对象
- */
- HomeadListModel model = JSONObject.parseObject(json, new TypeToken<HomeadListModel>() {
- }.getType());
- // HomeadListModel model2 = JSONObject.parseObject(json, HomeadListModel.class);
-
- /**
- * 根据对象获取json数据
- */
- String json1 = JSONObject.toJSONString(model);
- Log.i("aaa", "fastJson: " + json1);
-
- for (HomeadListModel.DataBean.HomeadlistBean data : model.data.homeadlist) {
- mData.add(imageUrl + data.imgurl);
- }
- runOnUiThread(new Runnable() {
- @Override
- public void run() {
- mAdapter.notifyDataSetChanged();
- }
- });
- }
- });
结尾:上面写了三种解析JSON数据的方法,第一种是最麻烦的,但是不一定是最差的,后面两种Gson和FastJson都是最常用的方法,本博客里面用到的API也是最常用的API,基本开发都够用了,其余未涉及到的请自行查看源码学习吧。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。