iOS JSON解析

NSJSONSerialization

NSJSONSerialization是iOS下用来解析JSONData的一个类,AFNetWorking下AFResponseSerialization中对于response的JSON处理也是用它来完成的。使用很简单。

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    NSDictionary *dic = @{
                          @"key":@"value"
                          };
    NSData *jsonData = [self convertToJsonDataWithObj:dic];
    NSLog(@"jsonString : %@",[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]);
    NSDictionary *jsonObj = [self convertToObjWithJsonData:jsonData];
    NSLog(@"jsonObj : %@",jsonObj);
}

- (NSData *)convertToJsonDataWithObj:(id)obj {
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:obj options:NSJSONWritingPrettyPrinted error:&error];
    return jsonData;
}

- (id)convertToObjWithJsonData:(NSData *)jsonData {
    return [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];
}

结果

jsonString : {
  "key" : "value"
}
 jsonObj : {
    key = value;
}

你可能感兴趣的:(iOS JSON解析)