NSArray *arrayOfAnthonysChildren = [[NSArray alloc]initWithObjects:@"Anthony's Son 1",@"Anthony's Danghter 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 dataWithISONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];
if([jsonData length]>0 && error == nil){
NSLog(@"Successfully serializes the dictionary into data = %@,jsonData");
}else if([jsonData length] == 0 && error == nil){
NSLog(@"No data returned after serialization.");
}else if(error != nil){
NSLog(@"An error happened = %@",error);
}
运行结果:
successfully serialized the dictionary into data.
JSON String = {
"Last Name" : "Robbins", "First Name" : "Anthony", "children" : [
"Anthony's Son 1", "Anthony's Daughter 1", "Anthony's Son 2", "Anthony's Son 3", "Anthony's Daughter 2"
],
"Age" : 51 }
把json数据转化成Arrays 或者Dictionaries
希望把一个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(@"Dersialized JSON Dictionary = %@",deserializedDictionary);
}else if([jsonObject isKindOfClass:[NSArray class]]){
NSArray *deserializedArray = (NSArray *)jsonObject;
NSLog(@"Dersialized JSON Array =%@",deserializedArray);
}
}
else if(error != nil){
NSLog(@"An error happened while deserializing the JSON data.");
}