Android新浪微博开发(3)JSon解析

  我在今天之前,可以说是没有接触过JSon的解析,今天就边学边总结,同时针对新浪微博返回的JSon进行解析,帮助自己巩固吧。我学习JSon解析是参考这个网址上的内容:http://lib.open-open.com/view/open1326376799874.html。一些JSon解析的基础知识和代码,大家可以看这篇文章。这边文章里面说,android2.3提供的JSon解析类,我使用的是android2.2,依然是提供JSon解析类的。

  现在开始针对新浪微博返回的数据来进行JSon解析,现在有这里有一个我发表一个微博成功之后返回的JSon数据。

{
    "created_at": "Wed Oct 10 14:20:07 +0800 2012",
    "id": 3499586935431840,
    "mid": "3499586935431840",
    "idstr": "3499586935431840",
    "text": "专注测试2天多",
    "source": "<a href=\"http://open.t.sina.com.cn\" 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": 2494519890,
        "idstr": "2494519890",
        "screen_name": "各种路各种盲",
        "name": "各种路各种盲",
        "province": "34",
        "city": "16",
        "location": "安徽 亳州",
        "description": "",
        "url": "",
        "profile_image_url": "http://tp3.sinaimg.cn/2494519890/50/5614603461/1",
        "profile_url": "u/2494519890",
        "domain": "",
        "weihao": "",
        "gender": "m",
        "followers_count": 1,
        "friends_count": 0,
        "statuses_count": 9,
        "favourites_count": 0,
        "created_at": "Wed Oct 26 11:01:04 +0800 2011",
        "following": false,
        "allow_all_act_msg": false,
        "geo_enabled": true,
        "verified": false,
        "verified_type": -1,
        "allow_all_comment": true,
        "avatar_large": "http://tp3.sinaimg.cn/2494519890/180/5614603461/1",
        "verified_reason": "",
        "follow_me": false,
        "online_status": 0,
        "bi_followers_count": 0,
        "lang": "zh-cn"
    },
    "reposts_count": 0,
    "comments_count": 0,
    "attitudes_count": 0,
    "mlevel": 0,
    "visible": {
        "type": 0,
        "list_id": 0
    }
}

  先来一个迭代解析整个JSon数据的样例,参数json是上面新浪微博返回的JSon数据。

 1 try
 2 {
 3     JSONObject jsonObject = new JSONObject(json);
 4     for (Iterator<?> iterator = jsonObject.keys(); iterator.hasNext();)
 5     {
 6         String key = (String) iterator.next();
 7         Object value = jsonObject.opt(key);
 8         if (value instanceof JSONObject)
 9         {
10             JSONObject new_value = (JSONObject) value;
11             for (Iterator<?> iterator2 =  new_value.keys(); iterator2.hasNext();)
12             {
13                 String key2 = (String) iterator2.next();
14                 Object value2 = new_value.opt(key2);
15                 System.out.println(key2 + "=" + value2);
16             }
17         }
18         else
19         {
20             System.out.println(key + "=" + jsonObject.opt(key));
21         }
22 
23     }
24 }
25 catch (JSONException e)
26 {
27     e.printStackTrace();
28 }

  因为iterator是与原来的JSon数据中元素的顺序是不同的,所以看到的输出也是不同的。

  新浪微博返回的JSon数据不可能说每一个元素对我们都是有用的,我们可以只是对某几个元素感兴趣,所以我们可以把我们感兴趣的那些元素提取出来。

  

 1 try
 2 {
 3     JSONObject jsonObject = new JSONObject(json);
 4     /* 从JSon中从指定的元素中获取整型 */
 5     String textString = jsonObject.getString("text");
 6     String usernameString = jsonObject.getJSONObject("user").getString("name");
 7     String timeString = jsonObject.getString("created_at");
 8 
 9     /* 从JSon中从指定的元素中获取整型 */
10     int reposts_count = jsonObject.getInt("reposts_count");
11     int comments_count = jsonObject.optInt("comments_count");
12 
13     /* 从JSon中从指定的元素中获取boolean类型 */
14     boolean favorited = jsonObject.getBoolean("favorited");
15 
16     /* 通过字符匹配构造适合中国人的时间字符串 */
17     SimpleDateFormat sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.US);
18     Date date = sdf.parse(timeString);
19     sdf.applyPattern("yyyy年MM月dd日hh时mm分ss秒");
20     timeString = sdf.format(date);
21 
22     StringBuffer sb = new StringBuffer();
23     sb.append(usernameString).append("在").append(timeString).append("发布了一条微博,内容是:").append(textString)
24             .append("。目前转发数为").append(reposts_count).append(",评论数为").append(comments_count);
25 
26     if (favorited)
27     {
28         sb.append("。已经收藏。");
29     }
30     else
31     {
32         sb.append("。尚未收藏。");
33     }
34 
35     Log.i("", sb.toString());
36 }
37 catch (Exception e)
38 {
39     e.printStackTrace();
40 }

  获取指定的元素的方法有两个,一个是get方法,一个是opt方法。二者的区别是:

  • get可以将要获取的键的值转换为指定的类型,如果无法转换或没有值则抛出JSONException
  • opt也是将要获取的键的值转换为指定的类型,无法转换或没有值时返回用户提供或这默认提供的值

   个人认为,使用opt方法会好一点,因为不会因为取值问题产生转化之类的异常。

 

  有时,新浪微博也会返回给我们一些JSon数组,例如我搜索关键词"阿信",新浪微博会返回给我下面的JSon数据。

 1 [
 2     {
 3         "screen_name": "阿信",
 4         "followers_count": 11091994,
 5         "uid": 1265020392
 6     },
 7     {
 8         "screen_name": "阿信星闻",
 9         "followers_count": 22427,
10         "uid": 1822541757
11     },
12     {
13         "screen_name": "阿信ken",
14         "followers_count": 10799,
15         "uid": 1870714545
16     },
17     {
18         "screen_name": "阿信歌友会",
19         "followers_count": 10493,
20         "uid": 1809449650
21     },
22     {
23         "screen_name": "阿信形象设计",
24         "followers_count": 10038,
25         "uid": 2122509095
26     },
27     {
28         "screen_name": "阿訫",
29         "followers_count": 515,
30         "uid": 1747978781
31     },
32     {
33         "screen_name": "阿信语录",
34         "followers_count": 4123,
35         "uid": 2091945521
36     },
37     {
38         "screen_name": "阿信-xiaoxiao",
39         "followers_count": 3761,
40         "uid": 2049489032
41     },
42     {
43         "screen_name": "阿信家的洗衣机",
44         "followers_count": 3526,
45         "uid": 1816621915
46     },
47     {
48         "screen_name": "阿信家的小胖话筒",
49         "followers_count": 2774,
50         "uid": 2728456684
51     }
52 ]

  解析代码:

 1 try
 2 {
 3     JSONArray jsonArray = new JSONArray(json);
 4     StringBuffer sb = new StringBuffer();
 5     for (int i = 0; i < jsonArray.length(); i++)
 6     {
 7         JSONObject jsonObject = jsonArray.getJSONObject(i);
 8         {
 9             String screen_name = jsonObject.optString("screen_name");
10             long followers_count = jsonObject.optLong("followers_count");
11             String uid = jsonObject.optString("uid");
12             sb.append("用户名:").append(screen_name).append("\n粉丝数:").append(followers_count).append("\nuid:")
13                     .append(uid).append("\n");
14             if (i != jsonArray.length() - 1)
15             {
16                 sb.append("--------------------------传说中的分隔线----------------------------\n");
17             }
18         }
19     }
20 
21     Log.i("", sb.toString());
22 }
23 catch (Exception e)
24 {
25     e.printStackTrace();
26 }

  另外,还有一些JSon中带有JSon类型的元素,即某一个元素的类型是一个JSon数据或者是一个JSon数据。这种情况只要获取到这个元素,继续进行JSon数据的解析就能继续解析了。

  至此,关于JSon的解析已经把经常使用到的方法都讲到了,关于JSon数据的构造由于在新浪微博中客户端并没有用到,所以就不在讲了。

  经过这3篇文章,我们就已经完全能够进行与新浪微博之间的交互,各个有权限的接口都可以使用,我们自己也能够实现自己的新浪微博客户端了。

posted @ 2012-10-11 10:47  猪圈里的猪  阅读(1080)  评论(0编辑  收藏  举报