关于JSON数据的解析总结——入门学习

直接上数据!

以下是两段包含不同内容的JSON数据(手动做了一些换行,便于观看)

{"status":"1","count":"1","info":"OK","infocode":"10000",
"lives":[{"province":"广东","city":"遂溪 
         县","adcode":"440823","weather":"晴","temperature":"26"
         ,"winddirection":"东","windpower":"≤3","humidity":"98"
         ,"reporttime":"2022-10-02 22:00:16"
         }
        ]
}

{"status":"1","count":"1","info":"OK","infocode":"10000",
"forecasts":[{
            "city":"遂溪县","adcode":"440823","province":"广东","reporttime":"2022-10-02 19:00:54",  
            "casts": [

    {"date":"2022-10-02","week":"7","dayweather":"阵雨","nightweather":"多云","daytemp":"31","nighttemp":"25","daywind":"北","nightwind":"北","daypower":"≤3","nightpower":"≤3"},
             {"date":"2022-10-03","week":"1","dayweather":"阵雨","nightweather":"多云","daytemp":"32","nighttemp":"25","daywind":"北","nightwind":"北","daypower":"≤3","nightpower":"≤3"},
             {"date":"2022-10-04","week":"2","dayweather":"多云","nightweather":"多云","daytemp":"32","nighttemp":"23","daywind":"北","nightwind":"北","daypower":"≤3","nightpower":"≤3"},
             {"date":"2022-10-05","week":"3","dayweather":"阵雨","nightweather":"阵雨","daytemp":"31","nighttemp":"24","daywind":"北","nightwind":"北","daypower":"≤3","nightpower":"≤3"}
                           ]   // "casts"内容结尾
                   }]            //"forecasts"内容结尾
}

从平台接口中获取回来的数据最初是用字符串进行存储,可以使用JSONObject中的fromObject静态方法进行将其转换为,JSONObject类的实例(依赖net.sf.json包)

JSONObject jsonObject=JSONObject.fromObject(line); 

然后再观察一下这两个数据,可以得出以下结论:

1. 在一个{.....}的数据应用于生成一个JSONObject类的一个实例,有多少个{..}就应该生成对应数目的JSONObject对象

2. 在一个[....]的数据应用于生成一个JSONArray类的一个实例,有多少个[..]就应该生成对应数目的JSONArray对象

3. 上述二者可以相互嵌套

4. 在{.....}中,数据的特征均为——“属性”:属性的值,"属性":[....]——即在JSONObject中嵌套      了JSONArray,{.....[....]....}的形式

    (1)对于前者,可通过JSONObject的成员方法getString,getInt的方法进行提取,参数为"属性"

 String nightWeather = objectCasts.getString("nightweather");
            //根据标识字符串,返回对应的整型数值
 int dayTemp = objectCasts.getInt("daytemp");

    (2)对于后者,即“属性”:后面跟着的是中括号[..]时,可通过JSONObject的成员方法getJSONArray()进行提取,参数为"属性"

 //把JSONObject中的通过标识“forecasts”将JSONArray提取出来
 JSONArray jsonArray1 = jsonObject.getJSONArray("forecasts");

5. 当JSONArray对象中嵌套着JSONObject,即中括号中嵌套大括号[...{...}...]时

    若只有一个{}那么其只嵌套了一个JSONObject数据,其下标为0;有多个{}时,则下标同数组中的顺序0,1,2....

     用例中属性“forcasts”:的JSONArray中只嵌套了一个JSONObject,期中的属性“casts”:的JSONArray中嵌套了多个个JSONObject

      

    此时可通过JSONArray的成员方法getJSONObject()方法进行提取,参数为下标值

//该JSONArray中只有1个JSONObject对象,其下标为0
JSONObject objectForecasts=jsonArray1.getJSONObject(0);

总的来说:

{ }对应JSONObject,[ ]对应JSONArray,二者可以嵌套;String转JSONObject时用静态方法fromobject();

JSONObject和JSONArray均有创建对方对象并返回的getJSONObject()或getJSONArray()方法;

对于其余属性,JSONObject均有getXXX()成员方法供获取其对应内容


可能不能帮助大家深入理解,但也许能帮助大家快速记忆和使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值