在iOS開發(fā)中,我們常常需要從服務(wù)器獲取數(shù)據(jù),而數(shù)據(jù)格式通常是JSON。但是JSON數(shù)據(jù)是無(wú)序的,如果不進(jìn)行解析,是無(wú)法使用其中的數(shù)據(jù)的。下面介紹幾種常用的iOS解析JSON數(shù)據(jù)的方法。
// json數(shù)據(jù) { "name":"張三", "age":18, "sex":"男", "hobbies":["唱歌","跳舞","打游戲"], "address":{ "province":"廣東", "city":"深圳", "district":"南山" } }
1. 使用Foundation框架自帶的JSON解析方法:NSJSONSerialization。
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *error; id json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]; if (json && [json isKindOfClass:[NSDictionary class]]) { NSDictionary *dict = (NSDictionary *)json; NSLog(@"%@", dict); }
2. 使用第三方框架YYModel。
@interface Person : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, assign) NSInteger age; @property (nonatomic, copy) NSString *sex; @property (nonatomic, strong) NSArray *hobbies; @property (nonatomic, strong) Address *address; @end Person *person = [Person yy_modelWithJSON:jsonString]; NSLog(@"%@", person.name);
3. 使用第三方框架Mantle。
@interface Person : MTLModel@property (nonatomic, copy) NSString *name; @property (nonatomic, assign) NSInteger age; @property (nonatomic, copy) NSString *sex; @property (nonatomic, strong) NSArray *hobbies; @property (nonatomic, strong) Address *address; @end Person *person = [MTLJSONAdapter modelOfClass:[Person class] fromJSONDictionary:jsonDict error:nil]; NSLog(@"%@", person.name);
以上是iOS中解析JSON無(wú)序數(shù)據(jù)的幾種方法,開發(fā)者可以根據(jù)項(xiàng)目需要選擇合適的方法。