JSON是一种数据交换语言,和XML是同样用途的。不过JSON的体积要比XML小,也就意味着在网络传输中速度会比XML更快。
JSON解析方法有几种:1.可以使用第三方框架SBJson,2.使用苹果提供的NSJSONSerialization
首先本地创建一个JSON文件,以便方便使用.
本地创建一个文件名为people.json的json文件,内容如下:
{
"people":[
{"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"},
{"firstName":"Jason","lastName":"Hunter","email":"bbbb"},
{"firstName":"Elliotte","lastName":"Harold","email":"cccc"}
]
}
1.SBJSON
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"people" ofType:@"json"];
NSString *jsonStr = [[NSString alloc] initWithContentsOfFile:jsonPath encoding:NSUTF8StringEncoding error:nil];
//创建一个解析器
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
//进行解析
NSMutableDictionary *dictJson = [jsonParser objectWithString:jsonStr];
//将结果写到plist文件中,以便看清楚结构
[dictJson writeToFile:@"/Users/apple/Desktop/abc.plist" atomically:YES];
NSArray *array = [dictJson objectForKey:@"people"];
for (NSDictionary *dict in array) {
NSLog(@"firstName : %@",[dict objectForKey:@"firstName"]);
NSLog(@"email : %@",[dict objectForKey:@"email"]);
}
写到abc.plist文件后,文件层次结构为:
根结构为people的字典,内有3个数组,数组为字典组成,字典中有3个key和value
2.NSJSONSerialization
NSString *jsonPath = [[NSBundle mainBundle] pathForResource:@"people" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:jsonPath];
NSMutableDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
NSArray *array = [dictJson objectForKey:@"people"];
for (NSDictionary *dict in array) {
NSLog(@"firstName : %@",[dict objectForKey:@"firstName"]);
NSLog(@"email : %@",[dict objectForKey:@"email"]);
}
结果当然跟SBJson的解析结果一样的.
--end