原文链接:
https://www.jianshu.com/p/b3fa693405a4
1、概念
JSON是一种轻量级的数据格式,用于数据交互服务器返回给客户端的数据。NSJSONSerialization是苹果原生的json解析方式,使用这个类可以将JSON转化为Foundation对象,也可将Foundatio对象转化为JSON。
2、使用NSJSONSerialization进行JSON解析的前提
An object that may be converted to JSON must have the following properties:
(1)顶层对象必须是NSArray或NSDictionary
(2) 所有对象必须是NSString,NSNumber,NSArray,NSDictionary or NULL
(3)所有字典的键值都是字符串类型的
(4)数值不能是非数值或无穷大
3、NSJSONReadingOptions参数的含义
typedef enum NSJSONReadingOptions : NSUInteger {
NSJSONReadingMutableContainers = (1UL << 0),//被创建的数字或字典是可变的
NSJSONReadingMutableLeaves = (1UL << 1),//Json对象中创建的字符串是NSMutableString
NSJSONReadingAllowFragments = (1UL << 2)//允许顶层对象不是NSArrayh
} NSJSONReadingOptions;
4、JSON 转化为 Foundation Object
-(NSDictionary *)objectConvertByJsonStr:(NSString *)jsonStr
{
NSData *data = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(@"error:%@",error);
}
return dict;
}
5、Foundation object 转化为 Json
-(NSString *)jsonStrConvertByObject:(NSDictionary *)dict
{
//whether a given object can be converted to JSON data.
if ([NSJSONSerialization isValidJSONObject:dict]) {
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *resultStr = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
return resultStr;
}else{
return nil;
}
}
网友评论