/*
总结: json格式的读写:
解析:
data = NSData dataWithContentsOfUrl:XXX
id obj = [ NSJsonSerialization NSJSONObjectWithData:data XXXX];
生成json格式的文件
array或 dict
NSData* data = [NSJSONSerialization dataWithJSONObject:array/dict XXXX];
data writeToFile:PATH;
或者
data writeToURL:(NSURL*)url;
*/
#define urlString @"http://localhost/files/test.json"
#define cpuString @"http://localhost/files/cpu.json"
void parseJsonData(void)
{
//将特殊字符编码,例如 中文
// urlString stringByAddingPercentEscapesUsingEncoding:<#(NSStringEncoding)#>
//将一些被编码的字符串解码成特殊字符中
// urlString stringByReplacingPercentEscapesUsingEncoding:<#(NSStringEncoding)#>
//将url字符串编码,即去除特殊字符串,若是没有特殊字符,可以不必
NSString* validUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL * url = [NSURL URLWithString:validUrlString ];
NSData* data = [ NSData dataWithContentsOfURL:url ];
NSString *contents = [[ NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"contents:%@",contents);
NSError* error=nil;
NSArray* array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
}
//********************************************
#define PATH @"/Users/wenhua/Desktop/write.json"
//把内存中的数据构造成json格式的字节流
void makeJsonData(void)
{
NSMutableArray *array = [[ NSMutableArray alloc]init];
[array addObject:@"abc"];
[array addObject:[NSNumber numberWithInt:123]];
[array addObject:[NSNumber numberWithBool:YES]];
[array addObject:[NSNumber numberWithFloat:3.14159]];
[array addObject:[NSNull null]];
//创建一个字典
NSDictionary* dict=@{@"k1":@"v1",@"k2":@"v2"};
[array addObject:dict];
NSArray* arr = @[@"one",@"two",@"three" ];
[array addObject:arr];
NSError* error=nil;
NSData* data = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error];
if (error) {
NSLog(@"%@",error);
return;
}
[data writeToFile:PATH atomically:YES];
}
原文:http://www.cnblogs.com/hyuganatsu/p/NSJSONSerialization.html