接着前面做的网络请求之后http://mengkang.net/390.html,做json
数据的解析。服务端返回的数据用jsonview
查看,如图:
最初我们我以为java里面的也会也有咱们大php里的json_decode的方法呢,我去,居然没有。好吧。下面是我用gson
来解析的笔记。
1.从数据结构上来看,是一个数组里面有三个对象,这三个对象还都是同一个类的实例。需要写一个供解析数据的时候反射的类。我定义为我indexFeed
2.解析json的数据的方法写在了JsonUtils
里。
indexFeed.java 的代码如下
package com.zhoumengkang.lqpark; /** * Created by zhoumengkang on 8/3/15. */ public class indexFeed { private String title; private String des; private String cover; public String getTitle(){ return title; } public void setTitle(String title){ this.title = title; } public String getDes(){ return des; } public void setDes(String des){ this.des = des; } public String getCover(){ return cover; } public void setCover(String cover){ this.cover = cover; } }
JsonUtils.java 的代码如下
package com.zhoumengkang.lqpark; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.LinkedList; /** * Created by zhoumengkang on 8/3/15. */ public class JsonUtils { public LinkedList<indexFeed> parseIndexFeedFromJson(String jsonData){ Type listType = new TypeToken<LinkedList<indexFeed>>(){}.getType(); Gson gson = new Gson(); LinkedList<indexFeed> indexFeeds = gson.fromJson(jsonData,listType); return indexFeeds; } }
最后调用使用gson解析出来的数据
JsonUtils jsonUtils = new JsonUtils(); LinkedList<indexFeed> indexFeeds = jsonUtils.parseIndexFeedFromJson(val); for (Iterator iterator = indexFeeds.iterator();iterator.hasNext();){ indexFeed indexFeed = (com.zhoumengkang.lqpark.indexFeed) iterator.next(); String des = indexFeed.getDes(); Log.i("-->", des); }
服务器端更多的用法类似于:
/** * 通过 id 列表获取 feed 缓存 * @param ids * @return */ public List<FeedLite> getFeedCache(String[] ids){ String key = RedisKeyManager.getFeedKey(); ICacheClient readClient = new ImplRedisDataReadClient(); List<String> jsonData = readClient.hmget(key,ids); readClient.release(); List<FeedLite> feedLites = new ArrayList<FeedLite>(); if (jsonData == null) { return feedLites; } Iterator<String> it = jsonData.iterator(); Gson gson = new Gson(); while (it.hasNext()){ FeedLite feedLite = gson.fromJson(it.next(),FeedLite.class); if (feedLite != null) { feedLites.add(feedLite); } } return feedLites; }