NSJSONSerialization
2018-04-03 本文已影响38人
oncezou
NSJSONSerialization是系统自带的解析JSON数据的类。
NSDictionary --> JSON
NSDictionary *dic = @{
@"time" : @"2018-04-03",
@"item" : @"NSJSONSerialization",
@"data" : @{
@"info": @"12"
}
};
NSString *filePath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
filePath = [filePath stringByAppendingPathComponent:@"dic"];
/* NSJSONWritingOptions 枚举
* NSJSONWritingPrettyPrinted 将JSON数据格式化,可读性高
* NSJSONWritingSortedKeys 不做任何操作,返回一串字符串
*/
NSError *error;
NSData *data = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
if (error){
NSLog(@"object to json data error");
return;
}else {
NSString *string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@",string);
}
/* NSJSONWritingPrettyPrinted 输出
{
"data" : {
"info" : "12"
},
"time" : "2018-04-03",
"item" : "NSJSONSerialization"
}
*/
// NSJSONWritingSortedKeys 输出 {"data":{"info":"12"},"item":"NSJSONSerialization","time":"2018-04-03"}
JSON --> NSDictionary
/* NSJSONReadingOptions 枚举
* NSJSONReadingMutableContainers 返回的是可变容器
* NSJSONReadingMutableLeaves 返回的内部的值可变对象
* NSJSONReadingAllowFragments 允许返回最外层既不是NSArray也不是NSDictionary,但必须是有效的JSON Fragment.
*/
NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
if (error) {
NSLog(@"json data to object error");
return;
}