IOS学习之路十九(JSON与Arrays 或者 Dictionaries相互转换)

今天写了个json与Arrays 或者 Dictionaries相互转换的例子很简单:

通过 NSJSONSerialization 这个类的 dataWithJSONObject: options: error:方法来实现。 

 //dictionary序列化成json
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:@"Anthony"forKey:@"First Name"];
    [dictionary setValue:@"Robbins"forKey:@"Last Name"];
    [dictionary setValue:[NSNumber numberWithUnsignedInteger:51]forKey:@"Age"];
    NSArray *arrayOfAnthonysChildren = [[NSArray alloc]
                                        initWithObjects:
                                        @"Anthony's Son 1", @"Anthony's Daughter 1", @"Anthony's Son 2", @"Anthony's Son 3", @"Anthony's Daughter 2",nil];
    [dictionary setValue:arrayOfAnthonysChildren forKey:@"children"];
    NSError *error = nil;
    //序列化数据成json的data。。。。。。。。。。。。。。。。。。。。。。。
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if ([jsonData length] > 0 && error == nil){
        NSLog(@"已把字典成功序列化.");
        //把json数据转化为String类型
        NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        NSLog(@"JSON String = %@", jsonString);
        
     //把 JSON 数据转化成 Arrays 或者 Dictionaries    
    //反序列化。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。
        id jsonObject = [NSJSONSerialization
                         JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments
                         error:&error];
        if (jsonObject != nil && error == nil){
            NSLog(@"反序列化成功...");
            if ([jsonObject isKindOfClass:[NSDictionary class]]){
                NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;
                NSLog(@"反序列化后的dictionary数据 = %@", deserializedDictionary);
            }
            else if ([jsonObject isKindOfClass:[NSArray class]]){
                NSArray *deserializedArray = (NSArray *)jsonObject;
                NSLog(@"反序列化json后的数组 = %@", deserializedArray);
            }else {
                
            }
        
        }else if (error != nil){
            NSLog(@"反序列化时发生一个错误");
        }
        
    } else if ([jsonData length] == 0 && error == nil){
       NSLog(@"序列化后没有返回数据");
    }else if (error != nil){
      NSLog(@"错误: %@", error);
    }
    
转载请注明:

本文转自:点击打开链接http://blog.csdn.net/wildcatlele

新浪微博:http://weibo.com/u/3202802157



原文地址:https://www.cnblogs.com/lixingle/p/3312961.html