一,代码。
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view. self.title=@"NSJSONSerialization"; [self initJson];
}
-(void)initJson
{
NSDictionary* jsonDic = [NSDictionary dictionaryWithObjectsAndKeys:@"李小华",@"name",@"女",@"sex",@"23",@"age",@"BeiJing",@"from",nil];
NSLog(@"-------------jsonDic--%@",jsonDic); //将Dic转为NSData
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:jsonDic options:NSJSONWritingPrettyPrinted error:nil];
//将NSData转为字符串
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"--jsonString--%@",jsonString);
NSLog(@"--jsonData---%@",jsonData); }
二,输出。
2015-10-22 15:04:05.112 NSJSONSerializationDemo[13058:272541] -------------jsonDic--{
age = 23;
from = BeiJing;
name = "\U674e\U5c0f\U534e";
sex = "\U5973";
}
2015-10-22 15:04:05.113 NSJSONSerializationDemo[13058:272541] --jsonString--{
"age" : "23",
"sex" : "女",
"name" : "李小华",
"from" : "BeiJing"
}
2015-10-22 15:04:05.113 NSJSONSerializationDemo[13058:272541] --jsonData---<7b0a2020 22616765 22203a20 22323322 2c0a2020 22736578 22203a20 22e5a5b3 222c0a20 20226e61 6d652220 3a2022e6 9d8ee5b0 8fe58d8e 222c0a20 20226672 6f6d2220 3a202242 65694a69 6e67220a 7d>