通过 NSJSONSerialization 这个类的 d ataWithJSONObject: 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);
- }