Json-framework for IOS

来源:互联网 发布:快压for mac 编辑:程序博客网 时间:2024/05/16 16:11
   JSON是一种轻量级的数据交换格式,易于阅读和理解,而且比xml要小很多。JSON是以键值对的形式组织的,具体介绍参见:http://www.json.org/json-zh.html

    目前很多语言都有相应的JSON解析框架,当然IOS使用的objective-c也不例外,有JSONKit(https://github.com/johnezang/JSONKit)、MTJSON(https://github.com/mysterioustrousers/MTJSON)、yajl-objc(https://github.com/gabriel/yajl-objc)、TouchJSON(https://github.com/TouchCode/TouchJSON)以及我一直在用的JSON-FrameWork(https://github.com/stig/json-framework/)。个人觉得json-framework有相当简单的API,使用起来很方便。它是一个开源框架,基于BSD协议发布。由于json-framework是开放源代码的,当你需要使用它时你只需将json的源代码加入到你的工程中。

   下面简单介绍一下如何使用json-framework将一个json格式的string转成object或者将object转成json格式的string。

//json string to object

 NSString *str =@"[{\"precision\": \"zip\",\"Latitude\":  37.7668,\"Longitude\": -122.3959,\"Address\":   \"\",\"City\":      \"SAN FRANCISCO\",\"State\":     \"CA\",\"Zip\":       \"94107\",\"Country\":   \"US\"},{\"precision\": \"zip\",\"Latitude\":  37.371991,\"Longitude\": -122.026020,\"Address\":   \"\",\"City\":      \"SUNNYVALE\",\"State\":     \"CA\",\"Zip\":       \"94085\",\"Country\":   \"US\"}]";

//[str JSONValue];可以使用这个直接转成object,也可以使用下面的方法

SBJsonParser *parser = [[[SBJsonParser alloc]init]autorelease];

NSError *error = nil;

id object = [parser objectWithString:strerror:&error];

if (!error && object) {

NSLog(@"object:%@",object);

for (id obj in object) {

NSLog(@"obj:%@",obj);

for (int i=0; i<[[objallKeys]count]; i++) {

NSLog(@"key:%@,value:%@",[[objallKeys]objectAtIndex:i],[objobjectForKey:[[objallKeys]objectAtIndex:i]]);

}

}//太蛋疼了,csdn这个编辑框居然无法排版

    }else

NSLog(@"error:%@",error);


//object to json string

NSMutableDictionary *dict = [[[NSMutableDictionary alloc]initWithCapacity:4]autorelease];

for (int i=0; i<4; i++) {

NSArray *array = [NSArray arrayWithObjects:@"gg",@"hh",@"ff",@"dd",nil];

[dict setObject:array forKey:[NSString stringWithFormat:@"%d",i]];

 }   

//[dict JSONRepresentation];可以使用这个直接转成json string,也可以使用下面的方法 

SBJsonWriter *writer = [[[SBJsonWriter alloc]init]autorelease];

NSString *bj = [writer stringWithObject:dicterror:&error];

if (!error && bj) {

NSLog(@"bj:%@",bj);

}else

NSLog(@"error:%@",error);

原创粉丝点击