AFNetworking解析Json-2-分类解释

来源:互联网 发布:网络教育的报名条件 编辑:程序博客网 时间:2024/06/05 23:01

AFK解析Json的使用-2-

AFK解析例子中,自带了两个分类(方法列表):NSDictionary+weather_package和NSDictionary+weather。这两个分类的方法就是专门解析出相应数据的。我们再来看一下Json的数据结构:

key为:data,值为:{

    "current_condition" =     (

                {

            cloudcover = 16;

            humidity = 59;

            "observation_time" = "09:09 PM";

            precipMM = "0.1";

            pressure = 1010;

            "temp_C" = 10;

            "temp_F" = 49;

            visibility = 10;

            weatherCode = 113;

            weatherDesc =             (

                                {

                    value = Clear;

                }

            );

            weatherIconUrl =             (

                                {

                    value = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png";

                }

            );

            winddir16Point = NW;

            winddirDegree = 316;

            windspeedKmph = 47;

            windspeedMiles = 29;

        }

    ); //---此处之前是key为 current_condition的部分


    request =     (

                {

            query = "Lat 32.35 and Lon 141.43";

            type = LatLon;

        }

    );

//---这是第2部分--key为 request


    weather =     (  //这里以后是第3部分--key为 weather

                {

            date = "2013-01-15";

            precipMM = "1.8";

            tempMaxC = 12;

             //---后面省略------

           

而 NSDictionary+weather_package.m的方法列表就是解析出这三个部分并转化为相应的数据结构:

-(NSDictionary *)currentCondition{

    NSDictionary *dict = [self objectForKey:@"data"];

    NSArray *ar = [dict objectForKey:@"current_condition"];

    return [ar objectAtIndex:0];

}


-(NSDictionary *)request{

    NSDictionary *dict = [self objectForKey:@"data"];

    NSArray *ar = [dict objectForKey:@"request"];

    return [ar objectAtIndex:0];

}


-(NSArray *)upcomingWeather{

    NSDictionary *dict = [self objectForKey:@"data"];

    return [dict objectForKey:@"weather"];

}

而其中数据比较重要的就是key为weather部分。所以又加了一个NSDictionary+weather的分类,专门解析里面的内容。例如其中一个方法是这么写的:

-(NSString *)weatherIconURL{

    NSArray *ar = [self objectForKey:@"weatherIconUrl"];

    NSDictionary *dict = [ar objectAtIndex:0];

    return [dict objectForKey:@"value"];

}

解析出来的值就是weatherIconUrl =             (

                                {

                    value = "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png";

                }

部分的png地址。

为了看字典内容,我自己添加了一个方法:

-(void)printDic    //打印字典的key和值

{

    for (NSString *key in self)

     {

         NSLog(@"key为:%@,值为:%@",key,[self objectForKey:key]);

     }

}

接下来通过一个具体的实例,来构建解析Json的应用--得到数据。

原创粉丝点击