iphone开发之Json数据的解析

网络中数据的传输往往是以Json或XML格式进行的,如新浪微博、腾讯微博、人人网等。今天主要介绍一下ios下Json数据的解析。

如果你还不了解什么是Json数据,请猛击。

首先是使用TouchJson进行解析:

TouchJson点击下载

首先导入

将Source文件加下的所以文件导入工程,在合适的位置添加CJSONDeserializer.h头文件

代码:

NSString *jsonStr = 

@"{\"customer\":[{\"name\":\"roamer\",\"ycount\":\"232.4\",\"sumcount\":\"322.3\"},{\"name\":\"王三\",\"ycount\":\"221.2\",\"sumcount\":\"1123.2\"},{\"name\":\"李四\",\"ycount\":\"1221.2\",\"sumcount\":\"12123.2\"}]}";

; NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding]; NSError *error; NSMutableDictionary *root = [[CJSONDeserializer deserializer] deserialize:jsonData error:&error]; NSLog(@"Customers:%@", root); NSMutableArray *customers = [root objectForKey:@"customer"]; NSString *jsonTextStr = @"姓名:\n"; for (NSMutableDictionary *customer in customers) { NSString *name = [customer objectForKey:@"name"]; name = [name stringByAppendingString:@"\n"]; jsonTextStr = [jsonTextStr stringByAppendingString:name]; NSLog(@"customer:%@",[customer objectForKey:@"name"]); }

输出结果:

Customers:{
    customer =     (
                {
            name = roamer;
            sumcount = "322.3";
            ycount = "232.4";
        },
                {
            name = "\U738b\U4e09";
            sumcount = "1123.2";
            ycount = "221.2";
        },
                {
            name = "\U674e\U56db";
            sumcount = "12123.2";
            ycount = "1221.2";
        }
    );
}
2012-06-15 14:08:20.406 TouchJsonTest[1495:f803] customer:roamer
2012-06-15 14:08:20.406 TouchJsonTest[1495:f803] customer:王三
2012-06-15 14:08:20.406 TouchJsonTest[1495:f803] customer:李四


下面使用SBJson

SBJson下载
首先导入

将Classes文件加下的所以文件导入工程,在合适的位置添加SBJson.h头文件

代码:

//解析数据
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSString *jsonStr = 

@"{\"customer\":[{\"name\":\"roamer\",\"ycount\":\"232.4\",\"sumcount\":\"322.3\"},{\"name\":\"王三\",\"ycount\":\"221.2\",\"sumcount\":\"1123.2\"},{\"name\":\"李四\",\"ycount\":\"1221.2\",\"sumcount\":\"12123.2\"}]}";

NSError *error = nil; NSMutableDictionary *root = [[NSMutableDictionary alloc] initWithDictionary:[parser objectWithString:jsonStr error:&error]]; //转换代码 不然会带来中文问题,诸如加()、:变成 = 等乱码问题 SBJsonWriter *jsonWrite = [[SBJsonWriter alloc] init]; NSString *jsonString = [jsonWrite stringWithObject:root]; NSLog(@"JsonString:%@", jsonString); [jsonWrite release]; NSMutableArray *customers = [root objectForKey:@"customer"]; NSLog(@"Customers:%@", customers); for (NSMutableDictionary *customer in customers) { NSLog(@"Customer-name:%@", [customer objectForKey:@"name"]); } [self.jsonData setText:@"解析完成"]; [self.parseBtn setTitle:@"Done" forState:UIControlStateNormal];

使用TouchJson和SBJson都可以快速的完成Json数据的解析,两者使用起来都比较简单,但TouchJson性能更好一些推荐使用。

有问题请留言,大家一起交流学习!
说明:转载请注明出处!


你可能感兴趣的:(ios,xml,json,新浪微博,腾讯,iPhone)