bjson有一個有用的sbjsonparser類,可以在一行內搞定整個json串的解析:
SBJsonParser *jsonParser = [[SBJsonParser alloc] init]; NSError *error = nil; NSArray *jsonObjects = [jsonParser objectWithString:jsonString error:&error]; [jsonParser release], jsonParser = nil;
sbjson將json作為objective-c的字典來處理。對於不同的webservice,你可能得到一個頂級的json對象或者一個數組。因此,objectWithString:error:有一個id類型返回值。你可以使用objective-c的動態特性來決定解析返回時采用何種數據來接收,如下:
id jsonObject = [jsonParser objectWithString:jsonString error:&error]; if ([jsonObject isKindOfClass:[NSDictionary class]]) // treat as a dictionary, or reassign to a dictionary ivar else if ([jsonObject isKindOfClass:[NSArray class]]) // treat as an array or reassign to an array ivar.
轉換代碼: 如果直接使用 NSMutableDictionary *root 來獲得 字符串,將會對json字串產生以下變化
1. 中文問題
2.加入了()符號
3.所有的: 變成了 =
要避免這個問題的產生,需要用
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonString = [jsonWriter stringWithObject:root];
[jsonWriter release];
這段代碼來把 NSMutableDictionary 轉成 NSString
SBJson的項目官網,以及源文件下載 https://github.com/stig/json-framework/downloads
xcode4.2.1 中使用 sbjson 的 3.1版本來解析json字符串:
http://blog.csdn.net/remote_roamer/article/details/7021640