JSON

IOS学习笔记(16)网络请求,json解析(4)

字号+ 作者:H5之家 来源:H5之家 2016-03-01 17:00 我要评论( )

NSArray *arrayOfAnthonysChildren = [[NSArray alloc]initWithObjects:@Anthonys Son 1,@Anthonys Danghter 1,@Anthonys Son 2,@Anthonys Son 3,@Anthonys Daughter 2,nil]; [dictionary setValue: arrayOfAnthony

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.");

}

 

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

相关文章
  • Json.Net学习笔记(十二) 协议解析

    Json.Net学习笔记(十二) 协议解析

    2016-03-01 16:00

  • 未来编程的9大猜想:JavaScript不必亲自编写

    未来编程的9大猜想:JavaScript不必亲自编写

    2016-01-30 13:01

  • Linux学习笔记:MySQL字符集

    Linux学习笔记:MySQL字符集

    2016-01-17 18:24

  • JSON学习笔记 陈建杭个人博客

    JSON学习笔记 陈建杭个人博客

    2016-01-17 12:22

网友点评