JSON解析(序列化和反序列化)

JSON的序列化,代码示例:

    NSDictionary *dic = @{@"name":@"zhuzhu", @"age":@25};
    if (![NSJSONSerialization isValidJSONObject:dic]) {
        NSLog(@"该对象不支持转换");
        return;
    }
    /**
     - Top level object is an NSArray or NSDictionary
     - All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
     - All dictionary keys are NSStrings
     - NSNumbers are not NaN or infinity
     */
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
    NSString *jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"%@", jsonStr);

JSON的反序列化,代码示例:

NSDictionary *dic = @{@"name":@"zhuzhu", @"age":@25};
    if (![NSJSONSerialization isValidJSONObject:dic]) {
        NSLog(@"该对象不支持转换");
        return;
    }
    /**
     - Top level object is an NSArray or NSDictionary
     - All objects are NSString, NSNumber, NSArray, NSDictionary, or NSNull
     - All dictionary keys are NSStrings
     - NSNumbers are not NaN or infinity
     */
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:kNilOptions error:nil];
  //
反序列的代码
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil]; NSLog(@"dic=%@", jsonDic);
原文地址:https://www.cnblogs.com/lyz0925/p/11578037.html