網絡中數據的傳輸往往是以Json或XML格式進行的,如新浪微博、騰訊微博、人人網等。今天主要介紹一下ios下Json數據的解析。
首先是使用TouchJson進行解析:
TouchJson點擊下載
首先導入
將Source文件加下的所以文件導入工程,在合適的位置添加CJSONDeserializer.h頭文件。
代碼:
- NSString *jsonStr = <p class="p1">@"{\"customer\":[{\"name\":\"roamer\",\"ycount\":\"232.4\",\"sumcount\":\"322.3\"},{\"name\":\"<span class="s1">王三</span>\",\"ycount\":\"221.2\",\"sumcount\":\"1123.2\"},{\"name\":\"<span class="s1">李四</span>\",\"ycount\":\"1221.2\",\"sumcount\":\"12123.2\"}]}"<span class="s2">;</span></p>;
- 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 = <p class="p1">@"{\"customer\":[{\"name\":\"roamer\",\"ycount\":\"232.4\",\"sumcount\":\"322.3\"},{\"name\":\"<span class="s1">王三</span>\",\"ycount\":\"221.2\",\"sumcount\":\"1123.2\"},{\"name\":\"<span class="s1">李四</span>\",\"ycount\":\"1221.2\",\"sumcount\":\"12123.2\"}]}"<span class="s2">;</span></p>
- 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性能更好一些推薦使用。