您的位置:首页 > Web前端 > JavaScript

解析JSON

2013-10-18 17:22 211 查看
iOS5新加了很多新功能,解析JSON也是其中的一个。

下面是我最近写的一个小DMEO。关于JSON的,现放出与大家共享。

以下代码参考Vandad Nahavandipoor的 《iOS 5 Programming Cookbook》。

这个是保存的方法。

- (IBAction)touchWriteButton:(id)sender {

NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];

[dictionary setValue:@"Anthony" forKey:@"First Name"];

[dictionary setValue:@"Robbins" forKey:@"Last Name"];

[dictionary setValue:[NSNumber numberWithUnsignedInteger:51] forKey:@"Age"];

NSArray *arrayOfAnthonysChildren = [[NSArray alloc] initWithObjects:

@"Anthony's Son 1", @"Anthony's Daughter 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 dataWithJSONObject:dictionary options:NSJSONWritingPrettyPrinted error:&error];

if (error) {

NSLog(@"dic->%@",error);

}

[dictionary release];

BOOL succeed = [jsonData writeToFile:JSON_PATH atomically:YES];

if (succeed) {

NSLog(@"Save succeed");

}else {

NSLog(@"Save fail");

}

}

这个是读取的方法。

- (IBAction)touchReadButton:(id)sender {

NSData *jsonData = [[NSData alloc] initWithContentsOfFile:JSON_PATH];

/* Now try to deserialize the JSON object into a dictionary */

NSError *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 {

NSLog(@"An error happened while deserializing the JSON data.");

}

}

[jsonData release];

}

此功能仅限于IOS5才能使用。他的解析效率是目前市面上最高的。iOS5系统API和5个开源库的JSON解析速度测试

XML和json都是用来保存、读取、传递数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: