首页 > 代码库 > NSArray与NSString、NSData,NSDictionary与NSString、NSData 相互转化
NSArray与NSString、NSData,NSDictionary与NSString、NSData 相互转化
NSArray *array = @[ @1, @2, @3, @4, @5, @3 ]; // 1. NSArray与NSData相互转化 // NSArray to NSData NSError *error; NSData *arrayData = [NSJSONSerialization dataWithJSONObject:array options:NSJSONWritingPrettyPrinted error:&error]; if (!error) { NSLog(@"arrayData = %@", arrayData); } else { NSLog(@"%@", error); } // NSData to NSArray NSArray *data2Array = [NSJSONSerialization JSONObjectWithData:arrayData options:NSJSONReadingMutableLeaves error:&error]; if (!error) { NSLog(@"data2Array = %@", data2Array); } else { NSLog(@"%@", error); } // 2. NSArray与NSString相互转化 // NSArray to NSString NSString *arrayStr = [array componentsJoinedByString:@","]; NSLog(@"arrayStr = %@", arrayStr); // NSString to NSArray NSArray *string2Array = [arrayStr componentsSeparatedByString:@","]; NSLog(@"string2Array = %@", string2Array); NSDictionary *dictionary = @{ @"name": @"xue zhang", @"sex": @1, @"age": @25 }; // 3. dictionary与NSData相互转化 // NSArray to NSData NSData *dictionaryData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error]; if (!error) { NSLog(@"dictionaryData = %@", dictionaryData); } else { NSLog(@"%@", error); } // NSData to NSDictionary NSDictionary *data2Dictionary = [NSJSONSerialization JSONObjectWithData:dictionaryData options:NSJSONReadingMutableLeaves error:&error]; if (!error) { NSLog(@"data2Dictionary = %@", data2Dictionary); } else { NSLog(@"%@", error); } // 4. NSDictionary与NSString相互转化 // NSDictionary to NSString NSString *dictionaryStr = [[NSString alloc] initWithData:dictionaryData encoding:NSUTF8StringEncoding]; NSLog(@"dictionaryStr = %@", dictionaryStr); // NSString to NSArray NSDictionary *string2Dictionary = [NSJSONSerialization JSONObjectWithData:[dictionaryStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:&error]; NSLog(@"string2Dictionary = %@", string2Dictionary);
NSArray与NSString、NSData,NSDictionary与NSString、NSData 相互转化
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。