ios開発におけるJSOnKitの使用

2526 ワード

ios開発におけるJSOnKitの使用
 
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]);

    }

 
 
 
//  strJson   json  ,

 #import "JSONKit.h"
NSString *strJson = @"{\"aps\": {\"alert\":{\"body\":\"a msg come!\"},\"bage\":3,\"sound\":\"def.mp3\"}}";
NSDictionary *result = [jsonData  objectFromJSONData];
 
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];