码迷,mamicode.com
首页 > 其他好文 > 详细

NSArray与NSString、NSData,NSDictionary与NSString、NSData 相互转化

时间:2014-10-09 02:24:08      阅读:180      评论:0      收藏:0      [点我收藏+]

标签:ios开发   nsstring   dictionary   nsarray   

    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 相互转化

标签:ios开发   nsstring   dictionary   nsarray   

原文地址:http://blog.csdn.net/yanglishuan/article/details/39896763

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