ios 使用json
1、從https://github.com/stig/json-framework/中下載json框架:json-framework
2、解壓下載的包,將class文件夾下的所有文件導入到當前工程下。
3、在使用的文件中加入導入語句 :#import "SBJson.h"
4、將json字符串轉為NSDictionary對象
- //測試json的解析
- -(void)testJsonParser: (NSString *) jsonString
- {
- jsonString = [[NSString alloc] initWithString:@"{\"userInfo\":{\"userName\":\"張三\",\"sex\":\"男\"}}"];
- NSLog(@"正在解析json字符串是:%@",jsonString);
- SBJsonParser * parser = [[SBJsonParser alloc] init];
- NSError * error = nil;
- NSMutableDictionary *jsonDic = [parser objectWithString:jsonString error:&error];
- NSMutableDictionary * dicUserInfo = [jsonDic objectForKey:@"userInfo"];
- NSLog(@"%@",[jsonDic objectForKey:@"userInfo" ]);
- NSLog(@"%@",[dicUserInfo objectForKey:@"userName"]);
- NSLog(@"%@",[dicUserInfo objectForKey:@"sex"]);
- } </ol> </div>
- NSString * customerGridJsonString = [[NSString alloc]initWithString:@" {\"customer\":[{\"name\":\"roamer\",\"ycount\":\"232.4\",\"sumcount\": \"322.3\"},{\"name\":\"王三\",\"ycount\":\"221.2\",\"sumcount\":\"1123.2 \"},{\"name\":\"李四\",\"ycount\":\"1221.2\",\"sumcount\":\"12123.2\"}]}"];
- SBJsonParser * parser = [[SBJsonParser alloc] init];
- // NSLog(@"%@",customerGridJsonString);
- NSError * error = nil;
- NSMutableDictionary *root = [[NSMutableDictionary alloc] initWithDictionary:[parser objectWithString:customerGridJsonString error:&error]];
- NSLog(@"%@",root);
- //注意轉換代碼
- SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
- NSString *jsonString = [jsonWriter stringWithObject:root];
- [jsonWriter release];
- NSLog(@"%@",jsonString);
- //注意轉換代碼
- NSMutableArray * customers = [root objectForKey:@"customer"];
- NSLog(@"%@",customers);
- for(NSMutableDictionary * member in customers)
- {
- NSLog(@"%@",[[member objectForKey:@"name"] description]);
- } </ol> </div>
- -(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]];
- }
- }
- } </ol> </div>
5、 處理json對象有多個記錄的方法</span>
6、遞歸遍歷解析出的NSDictionary對象
7、將解析出的NSDictionary對象還原為json字符串
</span>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!