在項目中常常會遇到解析json的狀況,若是想要解析JSON,那麼JSONKit能夠是一個不錯的選擇。git
git中JSONKit 的地址爲:https://github.com/johnezang/JSONKitgithub
因爲項目已經好久沒有更新,仍然使用了ARC,所以在使用時須要作幾處修改:json
1.把JSONKit設置爲不支持arc的模式,在Build Phases ->Compile Sources 選擇文件雙擊,在對話框中添加「-fno-objc-arc」參數(不含引號)。ui
2.此時編譯仍然會出現下面的報警:three
報錯信息:error: assignment to Objective-C‘s isa is deprecated in favor of object_setClass()string
解決辦法:it
(1)修改JSONKit.m文件第680行,修改成object_setClass(array, _JKArrayClass);io
(2)修改JSONKit.m文件第931行,修改成object_setClass(dictionary, _JKDictionaryClass);編譯
3.代碼實現class
用法:
1.dictionary------>json
NSString *jsonstring = [dictionary JSONString];
2.json------------>dictionary
NSDictionary *dictionary = [jsonstring objectFromJSONString];
//string to dictionary
NSString *resultStr = @"{\"name\": \"admin\",\"list\": [\"one\",\"two\",\"three\"]}";
NSData* jsonData = [resultStr dataUsingEncoding:NSUTF8StringEncoding];
NSLog(@"%@", [jsonData class]);
NSDictionary *resultDict = [jsonData objectFromJSONData];
NSLog(@"name is :%@",[resultDict objectForKey:@"name"]);
NSArray *list = [resultDict objectForKey:@"list"];
for (NSString *str in list) {
NSLog(@"list res:%@",str);
}
//dicttionary to string
NSString *jsonStr = [resultDict JSONString];
NSLog(@"temp is :%@",jsonStr);