以下代码都有详细的注释说明这些类型之间的转换(如有错误的地方还望批评指出,谢谢!)
- (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)#>] }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-19 12:34:00