码迷,mamicode.com
首页 > 移动开发 > 详细

【iOS】json格式转换

时间:2015-05-15 17:44:04      阅读:226      评论:0      收藏:0      [点我收藏+]

标签:json   objective-c   

NSString *str = nil;
    //字符串
    NSMutableString *string = [[NSMutableString alloc] init];
    [string appendString:@"xxxx"];
    str = [string JSONString];
    NSLog(@"str1:%@",[NSString stringWithString:str]);

//数组
    NSArray *array = [[NSArray alloc] initWithObjects:@"111",@"333",@"222", nil];
   // NSMutableArray *array = [NSMutableArray array];
    str = [array JSONString];
    NSLog(@"str2:%@",[NSString stringWithString:str]);
    [array release ];

//字典
    NSArray *firstArr = [NSArray arrayWithObjects:@"first",@"second", nil];
    //基本数据类型转换成NSNumber类型
    NSArray *secondArr = [NSArray arrayWithObjects:[NSNumber numberWithDouble:2.1],[NSNumber numberWithBool:NO], nil];
    //加到字典中
    NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:firstArr,@"first",secondArr,@"second", nil];
    //转化成json格式
    str = [dic JSONString];
    NSString *str2 = [NSString stringWithString:str];
    NSLog(@"str3:%@",str2);

//编码
    NSData *archive = [NSKeyedArchiver archivedDataWithRootObject:array];
//    NSLog(@"archive:%@",archive);
    NSArray *arr2 = [NSKeyedUnarchiver unarchiveObjectWithData:archive];
    NSLog(@"arr2:%@",arr2);


/*!

* @brief 把格式化的JSON格式的字符串转换成字典

* @param jsonString JSON格式的字符串

* @return 返回字典

*/

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {

if (jsonString == nil) {

return nil;

 

}

 

NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];

NSError *err;

NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData

options:NSJSONReadingMutableContainers

error:&err];

if(err) {

NSLog(@"json解析失败:%@",err);

return nil;

}

return dic;

}

 

+ (NSString*)dictionaryToJson:(NSDictionary *)dic

{

NSError *parseError = nil;

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];

return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

}




【iOS】json格式转换

标签:json   objective-c   

原文地址:http://blog.csdn.net/ytuzhangziyao/article/details/45747265

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!