1、从https://github.com/stig/json-framework/中下载json框架:json-framework
2、解压下载的包,将class文件夹下的所有文件导入到当前工程下。
3、在使用的文件中加入导入语句 :#import "SBJson.h"
4、将json字符串转为NSDictionary对象。
- NSString *temp=@"{"中国":{
- "北京":{"北京1":1,"北京2":2,"北京3":3},
- "上海":{"上海1":4,"上海2":5,"上海3":6},
- "广州":{"广州1":7,"广州2":8,"广州3":9}}}";
- NSDictionary *items = [temp JSONValue];
NSString *temp=@"{"中国":{ "北京":{"北京1":1,"北京2":2,"北京3":3}, "上海":{"上海1":4,"上海2":5,"上海3":6}, "广州":{"广州1":7,"广州2":8,"广州3":9}}}"; NSDictionary *items = [temp JSONValue];
5、递归遍历解析出的NSDictionary对象
- -(void)visitDict:(NSDictionary *)dict{
- NSArray *keys=[dict allKeys];
- for (NSString *key in keys) {
- NSString *result=[NSString stringWithFormat:@"key=%@,value=%@",key,[dict objectForKey:key]];
- NSLog(result);
- if([[dict objectForKey:key] isKindOfClass:[NSDictionary class]]){
- [self visitDict:[dict objectForKey:key]];
- }
- }
- }
-(void)visitDict:(NSDictionary *)dict{ NSArray *keys=[dict allKeys]; for (NSString *key in keys) { NSString *result=[NSString stringWithFormat:@"key=%@,value=%@",key,[dict objectForKey:key]]; NSLog(result); if([[dict objectForKey:key] isKindOfClass:[NSDictionary class]]){ [self visitDict:[dict objectForKey:key]]; } } }
6、将解析出的NSDictionary对象还原为json字符串
- NSString * jsonStr=[items JSONRepresentation];
NSString * jsonStr=[items JSONRepresentation];