- 在iOS中,JSON的常见解析方案有4种
第三方框架:JSONKit , SBJson , TouchJSON(性能从左到右,越差)
苹果原生(自带):NSJSONSerialization(性能最好)
NSJSONSerialization的常见方法
JSON数据—>OC对象
第一个参数:JSON的二进制数据
第二个参数:
NSJSONReadingMutableContainers = (1UL << 0), 可变字典和数组
NSJSONReadingMutableLeaves = (1UL << 1), 内部素有的字符串都是可变的,ios7之后有问题,一般不用
NSJSONReadingFragmentsAllowed = (1UL << 2), 既不是字典也不是数组,必须使用该枚举值
第三个参数:错误信息
+(id)JSONObjectWithData:(NSData *)data options:(NSJSONReadingOptions)opt error:(NSError **)error;
具体使用(看文件写的JSON返回值是什么,是字典就用字典接收,数组就用数组接收)
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"%@" , dict[@"error"]);
OC对象—>JSON数据
第一个参数:要转换的OC对象
第二个参数:
NSJSONWritingPrettyPrinted 排版,美观
第三个参数:错误信息
+(NSData *)dataWithJSONObject:(id)obj options:(NSJSONWritingOptions)opt error:(NSError **)error;
具体使用
NSDictionary *Mdict = @{
@"name":@"LHT",
@"age":@3
};
NSData *Data = [NSJSONSerialization dataWithJSONObject:Mdict options: NSJSONWritingPrettyPrinted error:nil];
NSLog(@"%@" ,[[NSString alloc] initWithData:Data encoding:NSUTF8StringEncoding] );
注意
- 并不是素有的OC对象都能转换为JSON(字符串类型的OC对象不可以转换)
最外层必须是 NSArray or NSDictionary
所有的元素必须是 NSString NSNumber NSArray NSDictionary orNSNull
字典中所有的key都必须是 NSStrins类型的
NSNumbers不能无穷大 - 我们可以利用方法判断一下
NSString *strM = @"LHT";
BOOL isValid = [NSJSONSerialization isValidJSONObject:strM];
if(isValid){
}
JSON数据与OC对象数据对应
JSON | OC |
---|---|
{} | @{} |
[] | @[] |
“” | @"" |
false | NSNumber 0 |
true | NSNumber 1 |
null | NSNull. 为空 |
//nil
[NSNull null]; //该方法获得的是一个单粒,表示为空,可以用在字典或者是数组中