zoukankan      html  css  js  c++  java
  • 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);


  • 相关阅读:
    Root of AVL Tree
    04-树4 是否同一棵二叉搜索树
    03-树3 Tree Traversals Again
    03-树2 List Leaves
    283. Move Zeroes
    506. Relative Ranks
    492. Construct the Rectangle
    476. Number Complement
    461. Hamming Distance
    389. Find the Difference
  • 原文地址:https://www.cnblogs.com/blfshiye/p/5422095.html
Copyright © 2011-2022 走看看