处理JSON格式的数据

  JSON格式的数据是最常用的数据格式,处理方法的选择就显得比较重要了。我常用的一种是用对象来接收,然后保存在数组中,需要时直接从数组中取值。下面列出一个小例子。

  1、在.h文件中:

#import <Foundation/Foundation.h>

 

@interface DailyWeathers : NSObject

@property(nonatomic,strong) NSString *date;

@property(nonatomic,strong) NSString *maxtempF;

@property(nonatomic,strong) NSString *mintempF;

@property(nonatomic,strong) NSURL *weatherIconUrl;

 

+(id)weatherWithJSON:(NSDictionary*)json;

 

@end

 

  2、在.m文件中:

#import "DailyWeathers.h"

 

@implementation DailyWeathers

 

+(id)weatherWithJSON:(NSDictionary *)json{

    return [[self alloc] initWithJSON:json];

}

 

-(id)initWithJSON:(NSDictionary*)json{

    self = [super init];

    if (self) {

        self.date = json[@"date"];

        self.maxtempF = json[@"maxtempF"];

        self.mintempF = json[@"mintempF"];

        self.weatherIconUrl = [NSURL URLWithString:json[@"hourly"][3][@"weatherIconUrl"][0][@"value"]];

    }

    return self;

}

 

@end

 

 

  3、在网络请求数据的地方,直接调用下面的方法:

-(NSArray*)dailyWeathersWithKeyFromJSON:(id)json{

    NSMutableArray *result = [NSMutableArray new];

    NSArray *weathers = json[@"data"][@"weather"];

    for (NSDictionary *weather in weathers) {

        DailyWeathers *dailyWeather = [DailyWeathers weatherWithJSON:weather];

        [result addObject:dailyWeather];

    }

    return [result copy];

}

 

  

posted on 2015-08-10 10:13  乱七八糟21号  阅读(625)  评论(0编辑  收藏  举报

导航