当你有一个 JSON 格式的数据,你希望将其反序列化为字典或数组时,你需要通过NSJSONSerialization 这个类的 JSONObjectWithData:options:error:方法来实现。我们已经知道如何把数组或者字典转化成 JSON 对象,其实是很简单的一个过程,那么把 JSON 对象转化成数组或者字典也是很简单的一件事情——使用 NSJSONSerialization 这个类的JSONObjectWithData:options:error:方法,这个方法返回的对象 要么是字典,要么是数组,这取决于我们传递给它的数据。下面是示例代码:


error = nil;
 
  
id jsonObject = [NSJSONSerialization
 
   
JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:&error];
if (jsonObject != nil &&error == nil){
      NSLog(@"Successfully deserialized...");
      if ([jsonObject isKindOfClass:[NSDictionary class]]){
     NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;     NSLog(@"Deserialized JSON Dictionary = %@", deserializedDictionary); 
}
else if ([jsonObject isKindOfClass:[NSArray class]]){
      NSArray *deserializedArray = (NSArray *)jsonObject;     NSLog(@"Deserialized JSON Array = %@", deserializedArray);
 } else{
}
 }
else if (error != nil){
     NSLog(@"An error happened while deserializing the JSON data."); 
   
}

如果我们将上面的代码与之前小节中的代码结合在一起,我们就可以首先将字典序列化为一个JSON 对象,然后再将这个 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;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted
error:&error];
if ([jsonData length] > 0 &&
error == nil){
     NSLog(@"Successfully serialized the dictionary into data.");

error = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments
error:&error]; 
   
if (jsonObject != nil &&error == nil)
{
 
   
    NSLog(@"Successfully deserialized...");
if ([jsonObject isKindOfClass:[NSDictionary class]]){
     NSDictionary *deserializedDictionary = (NSDictionary *)jsonObject;      NSLog(@"Deserialized JSON Dictionary = %@", deserializedDictionary); 
}
else if ([jsonObject isKindOfClass:[NSArray class]]){
   NSArray *deserializedArray = (NSArray *)jsonObject;   NSLog(@"Deserialized JSON Array = %@", deserializedArray);
 }
else {
}
 }
else if (error != nil){
     NSLog(@"An error happened while deserializing the JSON data.");
 }
 }
else if ([jsonData length] == 0 && error == nil){
     NSLog(@"No data was returned after serialization.");
 }
else if (error != nil){
    NSLog(@"An error happened = %@", error); 
   
}