您的位置:首页 > 移动开发 > IOS开发

iOSJsonKit的使用

2015-04-15 09:34 369 查看
转自:http://blog.csdn.net/cuiweijie3/article/details/9174739

ios开发中JSONKit的使用

 

C代码  


NSLog(@"打印测试");  

  

    NSString *jsonstring =@"[{\"age\":18,\"book\":{\"price\":23.2,\"title\":\"boook111\"},\"name\":\"samyou\"},{\"age\":22,\"book\":{\"price\":33,\"title\":\"booook222\"},\"name\":\"samsam\"}]";  

  

    NSData *data=[jsonstring dataUsingEncoding:NSUTF8StringEncoding];  

  

    NSArray *arr=(NSArray *)[data mutableObjectFromJSONData];  

  

    NSLog(@"count=%d",arr.count);  

  

    for(int i=0;i<arr.count;i++)  

  

    {  

  

        NSDictionary *people=[arr objectAtIndex:i];  

  

        NSString *name=[people objectForKey:@"name"];  

  

        NSString *age=[people objectForKey:@"age"];  

  

        NSLog(@"person withname=%@,age=%d",name,[age intValue]);  

  

        NSDictionary *book=[people objectForKey:@"book"];  

  

        NSString *bookname=[book objectForKey:@"title"];  

  

        NSNumber *price=[book objectForKey:@"price"];  

  

        NSLog(@"book with title=%@,price=%f",bookname,[price doubleValue]);  

  

    }  

 

 

 

C代码  


//比如 strJson 是网络上接收到的 json 字符串,  

  

 #import "JSONKit.h"  

NSString *strJson = @"{\"aps\": {\"alert\":{\"body\":\"a msg come!\"},\"bage\":3,\"sound\":\"def.mp3\"}}";  

NSDictionary *result = [jsonData  objectFromJSONData];  

 

C代码  


NSMutableDictionary *jsonDic = [NSMutableDictionary dictionary];  

NSMutableDictionary *alert = [NSMutableDictionary dictionary];  

NSMutableDictionary *aps = [NSMutableDictionary dictionary];  

[alert setObject:@"a msg come!" forKey:@"body"];  

[aps setObject:alert forKey:@"alert"];  

[aps setObject:@"3" forKey:@"bage" ];  

[aps setObject:@"def.mp3" forKey:@"sound"];  

[jsonDic setObject:aps forKey:@"aps"];  

NSString *strJson = [jsonDic JSONString];  

 

 

 

用法:

1.dictionary------>json

NSString *jsonstring = [dictionary JSONString];

 

 

2.json------------>dictionary

NSDictionary *dictionary = [jsonstring objectFromJSONString];
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息