博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
新浪微博数据Json格式解析
阅读量:7233 次
发布时间:2019-06-29

本文共 7999 字,大约阅读时间需要 26 分钟。

hot3.png

 

json结构的格式就是若干个 键/值(key, value) 对的集合,该集合可以理解为字典(Dictionary),每个 键/值 对可以理解成一个对象(Object)。 键/值 对中的 键(key) 一般是 一个string,值(value)可以是string、double、int等基本类型,也可以嵌套一个 键/值 对,也可以是一个数组,数组里面的数据的类型可以是基本类型,或者 键/值 对。可以看出 键/值 本来没什么,只是嵌套得多了就会觉得混乱,下面举个具体的例子来说明。注:该代码只是用来举例说明,并不能正确运行。

复制代码  

1             var testJson = {                        2                             "Name" :      "奥巴马" ,  3                             "ByName" :    ["小奥","小巴","小马"],  4                             "Education" : {
5                                            "GradeSchool" :  "华盛顿第一小学", 6                                            "MiddleSchool" : ["华盛顿第一初中" , "华盛顿第一高中"], 7                                            "University" :  { 8                                                               "Name" : "哈佛大学", 9                                                               "Specialty" : ["软件工程","会计"] 10                                                             } 11                                       } 12                         }

 

复制代码  

变量testJson就是一个json对象,testJson对象包括三个 键/值 对。

第一个 键/值 对: 键(key)是"Name“ ,其对应的值(value)是 "奥巴马" ,即 testJson["Name"]  == "奥巴马"

第二个 键/值 对: 键 是 "ByName" ,值是一个数组,是一个string集合。有必要的话,数组里面的元素也可以是 键/值 对。

第三个 键/值 对: 键 是 "Education",值是一个 Json对像,该json对象包括三个 键/值 对,这就是嵌套了。

总结:json对象就是若干个 键/值 对的集合,键是string,值可以是基本类型,或者嵌套一个Json对象,或者是一个数组(数组里的元素可以是基本类型,也可以是json对象,可以继续嵌套)。

获取名字:testJson["Name"]

获取第一个别名:testJson["ByName"][0] 。testJson的 键"ByName" 对应的值 是一个string数组 

获取小学名字: testJson["Education"]["GradeSchool"] , 获取大学主修专业:testJson["Education"]["University"]["Specialty"][0]

 

下面举个实例:

定义一个符合json格式要求的字符串:

string testJson = "{\"Name\" : \"奥巴马\",\"ByName\" : [\"小奥\",\"小巴\",\"小马\"],\"Education\":{\"GradeSchool\" : \"华盛顿第一小学\",\"MiddleSchool\" : [\"华盛顿第一初中\" , \"华盛顿第一高中\"], \"University\" :{ \"Name\" : \"哈佛大学\", \"Specialty\" : [\"软件工程\",\"会计\"]}}}";

 

然后需要用该字符串作为参数new 一个 JsonObject对象。微软自带的类库 System.Json ,然后添加命名空间 using System.Json;

主要代码就一句:JsonObject js = JsonObject.Parse(testJson); 用字符串testJson 作为参数new 一个 JsonObject 对象。通过监视我们可以看到js里面的内容和预料的一样,通过下面这幅图你应该可琢磨出很多东西来吧

 

在做这个之前我对JSON解析了解的不是很多,只能对一些简单的数据解析,对于稍微复杂一点的结构就一筹莫展了,在网上找了很多资料也没能解决

后来看了这个帖子,终于稍微摸到了一点门道:

首先先看一下新浪微博目前的JSON的结构

[html]                       

  1. {  

  2.     "statuses": [  

  3.         {  //位置1  

  4.             "created_at": "Tue May 31 17:46:55 +0800 2011",  // 位置2  

  5.             "id": 11488058246,  

  6.             "text": "求关注。",  

  7.             "source": "<a href="http://weibo.com" rel="nofollow">新浪微博</a>",  

  8.             "favorited": false,  

  9.             "truncated": false,  

  10.             "in_reply_to_status_id": "",  

  11.             "in_reply_to_user_id": "",  

  12.             "in_reply_to_screen_name": "",  

  13.             "geo": null,  

  14.             "mid": "5612814510546515491",  

  15.             "reposts_count": 8,  

  16.             "comments_count": 9,  

  17.             "annotations": [],  

  18.             "user": {  //位置3  

  19.                 "id": 1404376560,  

  20.                 "screen_name": "zaku",  

  21.                 "name": "zaku",  

  22.                 "province": "11",  

  23.                 "city": "5",  

  24.                 "location": "北京 朝阳区",  

  25.                 "description": "人生五十年,乃如梦如幻;有生斯有死,壮士复何憾。",  

  26.                 "url": "http://blog.sina.com.cn/zaku",  

  27.                 "profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1",  

  28.                 "domain": "zaku",  

  29.                 "gender": "m",  

  30.                 "followers_count": 1204,  

  31.                 "friends_count": 447,  

  32.                 "statuses_count": 2908,  

  33.                 "favourites_count": 0,  

  34.                 "created_at": "Fri Aug 28 00:00:00 +0800 2009",  

  35.                 "following": false,  

  36.                 "allow_all_act_msg": false,  

  37.                 "remark": "",  

  38.                 "geo_enabled": true,  

  39.                 "verified": false,  

  40.                 "allow_all_comment": true,  

  41.                 "avatar_large": "http://tp1.sinaimg.cn/1404376560/180/0/1",  

  42.                 "verified_reason": "",  

  43.                 "follow_me": false,  

  44.                 "online_status": 0,  

  45.                 "bi_followers_count": 215  

  46.             }  

  47.         },  

  48.         ...  

  49.     ],  

  50.     "previous_cursor": 0,  // 位置4  

  51.     "next_cursor": 11488013766,  

  52.     "total_number": 81655  

  53. }  

{    "statuses": [        {  //位置1            "created_at": "Tue May 31 17:46:55 +0800 2011",  // 位置2            "id": 11488058246,            "text": "求关注。",            "source": "
新浪微博",            "favorited": false,            "truncated": false,            "in_reply_to_status_id": "",            "in_reply_to_user_id": "",            "in_reply_to_screen_name": "",            "geo": null,            "mid": "5612814510546515491",            "reposts_count": 8,            "comments_count": 9,            "annotations": [],            "user": {  //位置3                "id": 1404376560,                "screen_name": "zaku",                "name": "zaku",                "province": "11",                "city": "5",                "location": "北京 朝阳区",                "description": "人生五十年,乃如梦如幻;有生斯有死,壮士复何憾。",                "url": "http://blog.sina.com.cn/zaku",                "profile_image_url": "http://tp1.sinaimg.cn/1404376560/50/0/1",                "domain": "zaku",                "gender": "m",                "followers_count": 1204,                "friends_count": 447,                "statuses_count": 2908,                "favourites_count": 0,                "created_at": "Fri Aug 28 00:00:00 +0800 2009",                "following": false,                "allow_all_act_msg": false,                "remark": "",                "geo_enabled": true,                "verified": false,                "allow_all_comment": true,                "avatar_large": "http://tp1.sinaimg.cn/1404376560/180/0/1",                "verified_reason": "",                "follow_me": false,                "online_status": 0,                "bi_followers_count": 215            }        },        ...    ],    "previous_cursor": 0,  // 位置4    "next_cursor": 11488013766,    "total_number": 81655}

#笔记#这里孙亿要提一下,使用新浪SDK获得的json字符串和官方网站上略有不同,不用第三方开源包获取到的Json数据是没有statuses的而且第一个字符是[ ],这里注意一下就行,以官方接口为主,可能是接口方法把前面的去掉了。

将上面的数据简化一下就是下面的结构,K代表key,V代表value

[html]                       

  1. {  

  2.     K : [     

  3.             {  // 位置1  

  4.                 K : V ,  // 位置2  

  5.                 K : { K : V }  // 位置3  

  6.             },  

  7.             {  // 位置1  

  8.                 K : V ,  // 位置2  

  9.                 K : { K : V }  // 位置3  

  10.             },  

  11.             ......  

  12.         ],  

  13.     K : V    // 位置4  

  14. }  

{	K : [   			{  // 位置1				K : V ,  // 位置2				K : { K : V }  // 位置3			},			{  // 位置1				K : V ,  // 位置2				K : { K : V }  // 位置3			},			......		],	K : V    // 位置4}

好了,现在我们开始一点一点的去解析它

首先最外面的一层大括号{ ..... },这个应该使用JSONObject()去获取对象

[html]                       

  1. JSONObject jsonObject = new JSONObject(json);   

JSONObject jsonObject = new JSONObject(json);

位置1的数据需要一个getJSONArray()方法去获取,因为他是一个数组,[ ]之间的每一个{ ..... }代表数组的一个元素

[html]                       

  1. JSONArray statusesArr = jsonObject.getJSONArray("statuses");  

JSONArray statusesArr = jsonObject.getJSONArray("statuses");

此时位置1的元素需要将其转化为JsonObject类

此时有2种办法可以转化

第一种:

[html]                       

  1. JSONObject statusesObj = statusesArr.getJSONObject(0);  // 这里的0代表的就是第一个{},以此类推  

JSONObject statusesObj = statusesArr.getJSONObject(0);  // 这里的0代表的就是第一个{},以此类推

第二种:

[html]                       

  1. String statusesStr = statusesArr.getString(0);  

  2. JSONObject statusesObj = new JSONObject(statusesStr);  

String statusesStr = statusesArr.getString(0);JSONObject statusesObj = new JSONObject(statusesStr);

这个时候我们就可以获取位置2的数据了

[html]                       

  1. statusesObj.getString("created_at");  

statusesObj.getString("created_at");

位置3的数据又有点比较搞了,直接贴代码

[html]                       

  1. String user = statusesObj.getString("user"); // 获取位置3的值  

  2. JSONObject userObj = new JSONObject(user); // 将其转化为JSONObject  

  3. String name = userObj.getString("name"); // 使用get方法获取数据  

String user = statusesObj.getString("user"); // 获取位置3的值JSONObject userObj = new JSONObject(user); // 将其转化为JSONObjectString name = userObj.getString("name"); // 使用get方法获取数据

位置4的数据获取很简单,使用普通的get方法就可以获得

[html]                       

  1. jsonObject.getInt("total_number");  

     

Java解析Json

 

包支持:org.json.jar

第一个:

String js = "{'a':'111','b':'333','c':'666'}";

   try {
    JSONObject jsonObject01 = new JSONObject(js);
    String a = jsonObject01.getString("a");
    String b = jsonObject01.getString("b");
    String c = jsonObject01.getString("c");
   
    System.out.println(a+b+c);
   } catch (JSONException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
   }
  

第二个:

String json = "{'name': '呵呵','array':[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],'address':'上海'}";

   try {
    JSONObject jsonObject = new JSONObject(json);
    String name = jsonObject.getString("name");
    String address = jsonObject.getString("address");

    System.out.println("name is:" + name);

    System.out.println("address is:" + address);

   
    JSONArray jsonArray = jsonObject.getJSONArray("array");
   
    for (int i = 0; i < jsonArray.length(); i++) {
     System.out.println("item " + i + " :" + jsonArray.getString(i));
    }
   } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }

转载于:https://my.oschina.net/u/1269935/blog/354319

你可能感兴趣的文章
MathExam小学一二年级计算题生成器V1.0
查看>>
数据转换例子
查看>>
BZOJ1901:Zju2112 Dynamic Rankings——题解
查看>>
BZOJ5334:[TJOI2018]数学计算——题解
查看>>
8.不绑定(ngNonBindable)
查看>>
新建一个虚拟机
查看>>
class path resource [applicationContext.xml] cannot be opened because it does not exis
查看>>
漫谈 Google 的 Native Client 技术(一)---- 历史动力篇(Web 本地计算发展史)
查看>>
SYN 和 RTO
查看>>
单元测试之NUnit
查看>>
java GC机制(转)
查看>>
linux,chmod如何更改所有子目录的权限,要包括隐藏文件
查看>>
js-时间戳转字符串
查看>>
dedecms 织梦 获取文章链接地址
查看>>
BZOJ1015【JSOI2008】星球大战 <离线并查集>
查看>>
深度学习【一】理解神经网络
查看>>
UML-------------------->类图
查看>>
The Little Prince-12/05
查看>>
ViewPager结合Fragment进行无限滑动
查看>>
安装mongo,新建数据库,添加普通用户
查看>>