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);


posted @ 2016-04-22 17:16  blfshiye  阅读(238)  评论(0编辑  收藏  举报