在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不能儲存基礎資料型別 (Elementary Data Type),所以所有的基礎資料型別 (Elementary Data Type)都是通過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.csdn.net/detail/samguoyi/4286190