在ios下解析json可以使用官方的库,下载地址https://github.com/johnezang/JSONKit
包里只有两个文件,jsonkit.h/jsonkit.m包含到类里面即可
//使用一个json字符串来作为被解析对象
NSString *jsonstring = @"[{\"age\":18,\"book\":{\"price\":23.2,\"title\":\"booooooook1\"},\"name\":\"samyou\"},{\"age\":22,\"book\":{\"price\":21,\"title\":\"booooooook2\"},\"name\":\"samsam\"}]";
//转换为nsdata为了模拟从http得到的json数据类型
NSData *data = [jsonstring dataUsingEncoding:NSUTF8StringEncoding];
//如果json串最外层是jsonarray则用mutableObjectFromJSONData,返回NSArray,否则用objectFromJSONData,返回NSDictionary
NSArray *arr = (NSArray *)[data mutableObjectFromJSONData];
NSLog(@"count=%d",arr.count);
for(int i=0;i<arr.count;i++)
{
NSDictionary *people = [arr objectAtIndex:i];
NSString *name = [people objectForKey:@"name"];
NSNumber *age = [people objectForKey:@"age"];//NSDictionary不能存储基本数据类型,所以所有的基本数据类型都是通过NSNumber封装
NSLog(@"person withname=%@,age = %d",name,[age intValue]);
NSDictionary *book = [people objectForKey:@"book"];
NSString *bookname = [book objectForKey:@"title"];
NSNumber *price = [book objectForKey:@"price"];
NSLog(@"book with title=%@, price=%f",bookname,[price doubleValue]);
}
哥的源代码下载地址
http://download.youkuaiyun.com/detail/samguoyi/4286190