NSJSONSerialization 实现JSON和Foundation Object的相互转化

南宫才艺
2023-12-01

NSJSONSerialization 实现JSON和Foundation Object的相互转化


你使用NSJSONSerialization类 转换JSON为Foundation 对象 和 转换Foundation 对为JSON.

对象能够转换为JSON必须有以下属性:

* 最顶层的对象是一个NSArray或者NSDictionary
* 所有对象的实例是NSStringNSNumberNSArrayNSDictionary, or NSNull
* 所有NSDictionary的keys是NSString
* Numbers 不是 NaN or infinity (Not a Number 或者无穷的)

能够调用 isValidJSONObject: 或者尝试一次转化限定的方式去判断是否给定的对象能够转化为JSON数据 


    // 1.JOSN数据转为Foundation Object
    //  JOSN字符串
    NSString *josnStr = @"{\"username\":\"lili\",\"password\":\"123\",\"sex\":\"F\",}";
    
    // 转化为Data
    NSData *dataStr = [josnStr dataUsingEncoding:NSUTF8StringEncoding];
    
    // NSJSONSerialization 解析,用字典接收
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:dataStr options:NSJSONReadingMutableContainers error:nil];
    /*
     enum {
     NSJSONReadingMutableContainers = (1UL << 0),
     NSJSONReadingMutableLeaves = (1UL << 1),
     NSJSONReadingAllowFragments = (1UL << 2)
     };
     typedef NSUInteger NSJSONReadingOptions;
     */
    
    
    
    NSLog(@"dict = %@",dict);
    /*输出
     dict = {
     password = 123;
     sex = F;
     username = lili;
     }

     */

    // 2.将字典对象转为JOSN数据
    
    // 先判断dict对象是否符合转化
    if ([NSJSONSerialization isValidJSONObject:dict]) {
        
        // 将字典对象转换为JOSN数据
        NSData *JOSNdata = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
        
        NSString *str = [[NSString alloc] initWithData:JOSNdata encoding:NSUTF8StringEncoding];
        NSLog(@"STR = %@",str);
        /*输出
         STR = {
         "username" : "lili",
         "sex" : "F",
         "password" : "123"
         }
         */
        
    }
    
 
    NSMutableDictionary *dict2 = [NSMutableDictionary dictionary];
    NSString *pathStr = @"/Users/JSON.txt";
    
    NSOutputStream *outputStream = [[NSOutputStream alloc] initToFileAtPath:pathStr append:YES];
    [outputStream open];
    
    NSInteger length = [NSJSONSerialization writeJSONObject:dict2 toStream:outputStream options:NSJSONWritingPrettyPrinted error:nil];
    NSLog(@"length = %d",length);
    [outputStream close];
    
    
    
    NSInputStream *inStream = [[NSInputStream alloc]initWithFileAtPath:pathStr];
    [inStream open];
    id streamObject = [NSJSONSerialization JSONObjectWithStream:inStream options:NSJSONReadingAllowFragments error:nil];
    if ([streamObject isKindOfClass:[NSDictionary class]]) {
        NSDictionary *jsonDictionary = (NSDictionary*)streamObject;
        NSNumber *ageNumber = (NSNumber*)[jsonDictionary valueForKey:@"age"];
        NSLog(@"username:%@ And age:%d",[jsonDictionary valueForKey:@"username"],[ageNumber intValue]);
    }
    [inStream close];


 类似资料: