标签:数据类型 转换 nsdictionary nsstring json
- (void)viewDidLoad { [super viewDidLoad]; /** * NSDictionary ||NSArray(NSMutableArray) ==>> NSData ==>> NSString (Json): */ // NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys: // @"balance", @"key", // @"remaining balance", @"label", // @"45", @"value", // @"USD", @"currencyCode",nil]; NSArray *params = @[@"balance", @"key", @"remaining balance", @"label", @"45", @"value", @"USD", @"currencyCode"]; NSError *error = nil; NSData *jsonData = [NSJSONSerialization dataWithJSONObject:params options:NSJSONWritingPrettyPrinted error:&error]; NSString *jsonString; if ([jsonData length] > 0 && error == nil){ jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]; NSLog(@"%@",jsonString); }else{ NSLog(@"Erroe:%@",error); } /** * NSString (Json): ==>>NSData ==>> NSDictionary ||NSArray(NSMutableArray) */ //将NSString转化为NSData NSData *jsonData2 = [jsonString dataUsingEncoding:NSUTF8StringEncoding]; NSError *error2 = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData2 options:kNilOptions error:nil]; if (jsonObject != nil && error2 == nil){ NSLog(@"jsonObject == %@",jsonObject); }else{ // 解析错误 NSLog(@"Erroe:%@",error2); } /** NSData -> NSString :returns: NSString */ // NSString *tempStr = [[NSString alloc] initWithData:<#(NSData *)#> encoding:<#(NSStringEncoding)#>]; /** NSString -> NSData */ // NSData *tempData = [[[NSString alloc]init] dataUsingEncoding:<#(NSStringEncoding)#>] }
版权声明:本文为博主原创文章,未经博主允许不得转载。
NSDictionary 或者NSArray(NSMutableArray) ==>> NSData ==>> NSString (Json):
标签:数据类型 转换 nsdictionary nsstring json
原文地址:http://blog.csdn.net/red_coraldown/article/details/47101345