【www.bbyears.com--ios】
ios5中apple增加了解析JSON的api——NSJSONSerialization。网上已经有人做过测试,NSJSONSerialization在效率上完胜SBJSON、TouchJSON、YAJL、JSONKit、NextiveJson。详情见这里。既然apple为我们提供了这么良好的工具,我们没理由不用吧。
NSJSONSerialization提供了将JSON数据转换为Foundation对象(一般都是NSDictionary和NSArray)和Foundation对象转换为JSON数据(可以通过调用isValidJSONObject来判断Foundation对象是否可以转换为JSON数据)。
解析JSON数据,转换为NSData格式
代码如下
NSError *jsonError;
NSData *objectData = [content2 dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&jsonError];
数值转换为字符串
代码如下
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary
options:0 // OR NSJSONWritingPrettyPrinted
error:&error];
NSString *jsonString;
if (! jsonData) {
NSLog(@"bv_jsonStringWithPrettyPrint: error: %@", error.localizedDescription);
jsonString = @"{}";
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSJSONWritingPrettyPrinted是可读性的字符串,0则不换行的格式