Gson解析新浪微博数据


JSON是JavaScript Object Notation的缩写,可见JSON来源于JavaScript。JSON数据是一系列键值对的集合。

JSON和XML的比较

  • JSON比XML体积小
  • JSON和JavaScript交互更加方便
  • JSON对数据的描述性没有XML好
  • JSON的速度要远远大于XML
  • JSON的解析要比XML的解析要方便

JSON已经被大多数开发人员所接受,在网络数据的传输当中应用非常广泛

Json的规格非常简单,只用一个页面几百个字就能说清楚,而且Douglas Crockford声称这个规格永远不必升级,因为该规定的都规定了。

1) 并列的数据之间用逗号(",")分隔。

2) 映射用冒号(":")表示。

3) 并列数据的集合(数组)用方括号("[]")表示。

4) 映射的集合(对象)用大括号("{}")表示。


详情请看:http://www.json.org/json-zh.html


JSON文件格式化工具:http://jsonformatter.curiousconcept.com/


新浪微博的部分部件格式就像下面所示:在源码里有完整的微博数据,一次可以接收20篇微博。

{
   "statuses":[
      {
         "created_at":"Fri May 18 09:25:28 +0800 2012",
         "id":3446966543302976,
         "mid":"3446966543302976",
         "idstr":"3446966543302976",
         "text":"知,和行之间,是质一般的鸿沟。很多人讲起道理来头头是道,做起事来一无所知,道理只是用来说的。",
         "source":"<a href=\"http://www.xiaomi.com\" rel=\"nofollow\">小米手机</a>",
         "favorited":false,
         "truncated":false,
         "in_reply_to_status_id":"",
         "in_reply_to_user_id":"",
         "in_reply_to_screen_name":"",
         "geo":null,
         "user":{
            "id":1558247760,
            "idstr":"1558247760",
            "screen_name":"许单单",
            "name":"许单单",
            "province":"11",
            "city":"2",
            "location":"北京 西城区",
            "description":"专注互联网行业趋势、竞争格局和资本定价。【免责声明】本微博一切言论仅代表个人观点,旨在交流投资经验和教训,不构成任何投资建议。",
            "url":"http://blog.sina.com.cn/xudandanpku",
            "profile_image_url":"http://tp1.sinaimg.cn/1558247760/50/5610765032/1",
            "profile_url":"xddpku",
            "domain":"xddpku",
            "weihao":"",
            "gender":"m",
            "followers_count":143057,
            "friends_count":932,
            "statuses_count":6027,
            "favourites_count":568,
            "created_at":"Mon Mar 15 11:56:26 +0800 2010",
            "following":true,
            "allow_all_act_msg":false,
            "geo_enabled":false,
            "verified":true,
            "verified_type":0,
            "remark":"",
            "allow_all_comment":false,
            "avatar_large":"http://tp1.sinaimg.cn/1558247760/180/5610765032/1",
            "verified_reason":"Danseq投资咨询公司CEO,3W咖啡创始人",
            "follow_me":false,
            "online_status":0,
            "bi_followers_count":654,
            "lang":"zh-cn"
         },
         "reposts_count":1,
         "comments_count":0,
         "mlevel":0,
         "visible":{
            "type":0,
            "list_id":0
         }
      },
      {
         "created_at":"Fri May 18 09:25:13 +0800 2012",
         "id":3446966480167755,
         "mid":"3446966480167755",
         "idstr":"3446966480167755",
         "text":"北朝鲜这批泼水无赖,小人之尤!近则不逊,远则怨!天天喂他,还要咬人!石油能源粮食日用品都靠中国,全是倒贴!",
         "source":"<a href=\"http://m.weibo.com/web/cellphone.php#ipad\" rel=\"nofollow\">iPad客户端</a>",
         "favorited":false,
         "truncated":false,
         "in_reply_to_status_id":"",
         "in_reply_to_user_id":"",
         "in_reply_to_screen_name":"",
         "geo":null,
         "user":{
            "id":1813080181,
            "idstr":"1813080181",
            "screen_name":"薛蛮子",
            "name":"薛蛮子",
            "province":"11",
            "city":"5",
            "location":"北京 朝阳区",
            "description":"天使投资人薛蛮子 商业计划书请发信箱[email protected]或ctquan.com/manzi",
            "url":"",
            "profile_image_url":"http://tp2.sinaimg.cn/1813080181/50/5615039894/1",
            "profile_url":"charlesxue",
            "domain":"charlesxue",
            "weihao":"",
            "gender":"m",
            "followers_count":2751028,
            "friends_count":1629,
            "statuses_count":44510,
            "favourites_count":866,
            "created_at":"Mon Sep 06 00:00:00 +0800 2010",
            "following":true,
            "allow_all_act_msg":true,
            "geo_enabled":true,
            "verified":true,
            "verified_type":0,
            "remark":"",
            "allow_all_comment":true,
            "avatar_large":"http://tp2.sinaimg.cn/1813080181/180/5615039894/1",
            "verified_reason":"天使投资人、微博打拐发起人之一",
            "follow_me":false,
            "online_status":1,
            "bi_followers_count":1329,
            "lang":"zh-cn"
         },
         "retweeted_status":{
            "created_at":"Thu May 17 18:53:02 +0800 2012",
            "id":3446746988027751,
            "mid":"3446746988027751",
            "idstr":"3446746988027751",
            "text":"【外交部:中方要求朝方确保中国船员安全】针对3艘中国渔船近日被朝鲜方面抓扣报道,中国外交部下午称,中方正通过有关渠道与朝方保持密切沟通,争取有关问题尽早得到妥善解决。中方要求朝方确保中国船员安全与合法权益。答问实录:http://t.cn/zOm5zjU",
            "source":"<a href=\"http://weibo.com/\" rel=\"nofollow\">新浪微博</a>",
            "favorited":false,
            "truncated":false,
            "in_reply_to_status_id":"",
            "in_reply_to_user_id":"",
            "in_reply_to_screen_name":"",
            "geo":null,
            "user":{
               "id":1618051664,
               "idstr":"1618051664",
               "screen_name":"头条新闻",
               "name":"头条新闻",
               "province":"11",
               "city":"8",
               "location":"北京 海淀区",
               "description":"每日播报全球各类重要资讯、突发新闻,全天24小时即时发布。欢迎报料、投稿,请发私信或者邮件:[email protected]。",
               "url":"http://news.sina.com.cn/",
               "profile_image_url":"http://tp1.sinaimg.cn/1618051664/50/5631943776/0",
               "profile_url":"breakingnews",
               "domain":"breakingnews",
               "weihao":"",
               "gender":"f",
               "followers_count":12861287,
               "friends_count":89,
               "statuses_count":47001,
               "favourites_count":6,
               "created_at":"Fri Aug 28 16:34:36 +0800 2009",
               "following":false,
               "allow_all_act_msg":true,
               "geo_enabled":true,
               "verified":true,
               "verified_type":3,
               "remark":"",
               "allow_all_comment":true,
               "avatar_large":"http://tp1.sinaimg.cn/1618051664/180/5631943776/0",
               "verified_reason":"新浪新闻中心24小时播报全球重大新闻",
               "follow_me":false,
               "online_status":1,
               "bi_followers_count":80,
               "lang":"zh-cn"
            },
            "reposts_count":1058,
            "comments_count":855,
            "mlevel":0,
            "visible":{
               "type":0,
               "list_id":0
            }
         },
         "reposts_count":2,
         "comments_count":0,
         "mlevel":0,
         "visible":{
            "type":0,
            "list_id":0
         }
      },   
    ],
   "hasvisible":false,
   "previous_cursor":0,
   "next_cursor":3446963247215854,
   "total_number":2196

主界面:使用Gson解析json数据可以很方便的就把数据和java 类互相转换。因为微博JSON数据

public class ParseJsonMain extends Activity {
	/** Called when the activity is first created. */
	TextView jsonTv,userTv;
	InputStream in;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		jsonTv=(TextView)findViewById(R.id.json_show);
		userTv=(TextView)findViewById(R.id.user_json_show);
		Gson gson = new Gson(); 
		WeiboObject response = gson.fromJson(getJsonData("weibo.json"),WeiboObject.class); 
		jsonTv.setText(""+response.next_cursor);
		List<StatusesInfo> results = response.statuses;
		StringBuilder sb=new StringBuilder();
		StringBuilder idShow=new StringBuilder();
		StringBuilder retweeed=new StringBuilder();
		int n=0;
		for (StatusesInfo result : results) {
				sb.append(result.created_at+"\n");
				if(result.retweeted_status==null){
					n++;
				}else{
					retweeed.append(result.retweeted_status.text+"\n");
				}
				idShow.append(result.visible.list_id+"\n");
		}
		Log.e("kingfly", "id="+idShow);
		Log.e("kingfly", ""+n);
		userTv.setText(sb.toString()+"\n"+retweeed.toString());
		
	}
	
	public String getJsonData(String fileName) {
		String x = null;
		try {
			InputStream in = getResources().getAssets().open(fileName);
			x = fileToString(in, "UTF-8");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return x;
	}

	public static String fileToString(InputStream in, String charset) {
		StringBuffer sb = new StringBuffer();
		try {
			LineNumberReader reader = new LineNumberReader(new BufferedReader(
					new InputStreamReader(in, charset)));
			String line;
			while ((line = reader.readLine()) != null) {
				sb.append(line).append(System.getProperty("line.separator"));
			}
			reader.close();
		} catch (UnsupportedEncodingException e) {
		} catch (IOException e) {
		}
		return sb.toString();
	}
}



这里主要是注意类对象,这个必须没有问题,才能正常的解析数据。

public class WeiboObject {
	public List<StatusesInfo> statuses;
	
	 @SerializedName("hasvisible")
	public boolean hasvisible;
	 
	 @SerializedName("previous_cursor")
	public int previous_cursor;
	 
	 @SerializedName("next_cursor")
	public String next_cursor; 
	 
	 @SerializedName("total_number")
	public int total_number;
}

public class StatusesInfo {

	public String created_at;
	public String id; // change to int
	public String idstr;
	public String text;
	public boolean favorited;
	public boolean truncated;
	public String in_reply_to_status_id;
	public String in_reply_to_user_id;
	public String in_reply_to_screen_name;
	public List<GeoInfo> geo;
	public String mid; // change to int
	public int reposts_count;
	public int comments_count;
	public int melvel;
	public VisibleInfo visible;
	public UserInfo user;
	public RetweetedStatus retweeted_status;
	public String source;
	
	public List<GeoInfo> getGeo() {
		return geo;
	}

	public void setGeo(List<GeoInfo> geo) {
		this.geo = geo;
	}

	public String getIdstr() {
		return idstr;
	}

	public void setIdstr(String idstr) {
		this.idstr = idstr;
	}

	public UserInfo getUser() {
		return user;
	}

	public void setUser(UserInfo user) {
		this.user = user;
	}

	public String getSource() {
		return source;
	}

	public void setSource(String source) {
		this.source = source;
	}

	public String getCreated_at() {
		return created_at;
	}

	public void setCreated_at(String created_at) {
		this.created_at = created_at;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text;
	}

	public boolean isFavorited() {
		return favorited;
	}

	public void setFavorited(boolean favorited) {
		this.favorited = favorited;
	}

	public boolean isTruncated() {
		return truncated;
	}

	public void setTruncated(boolean truncated) {
		this.truncated = truncated;
	}

	public String getIn_reply_to_status_id() {
		return in_reply_to_status_id;
	}

	public void setIn_reply_to_status_id(String in_reply_to_status_id) {
		this.in_reply_to_status_id = in_reply_to_status_id;
	}

	public String getIn_reply_to_user_id() {
		return in_reply_to_user_id;
	}

	public void setIn_reply_to_user_id(String in_reply_to_user_id) {
		this.in_reply_to_user_id = in_reply_to_user_id;
	}

	public String getIn_reply_to_screen_name() {
		return in_reply_to_screen_name;
	}

	public void setIn_reply_to_screen_name(String in_reply_to_screen_name) {
		this.in_reply_to_screen_name = in_reply_to_screen_name;
	}


	public String getMid() {
		return mid;
	}

	public void setMid(String mid) {
		this.mid = mid;
	}

	public int getReposts_count() {
		return reposts_count;
	}

	public void setReposts_count(int reposts_count) {
		this.reposts_count = reposts_count;
	}

	public int getComments_count() {
		return comments_count;
	}

	public void setComments_count(int comments_count) {
		this.comments_count = comments_count;
	}

	public int getMelvel() {
		return melvel;
	}

	public void setMelvel(int melvel) {
		this.melvel = melvel;
	}

	public VisibleInfo getVisible() {
		return visible;
	}

	public void setVisible(VisibleInfo visible) {
		this.visible = visible;
	}

	public RetweetedStatus getRetweeted_status() {
		return retweeted_status;
	}

	public void setRetweeted_status(RetweetedStatus retweeted_status) {
		this.retweeted_status = retweeted_status;
	}

}

以此类推,来分解json数据。


程序运行结果:

Gson解析新浪微博数据_第1张图片



源码下载:

http://download.csdn.net/detail/comkingfly/4311809


你可能感兴趣的:(JavaScript,json,新浪微博,String,user,Comments)