ios 使用json

jopen 11年前

1、从https://github.com/stig/json-framework/中下载json框架:json-framework

2、解压下载的包,将class文件夹下的所有文件导入到当前工程下。

3、在使用的文件中加入导入语句 :#import "SBJson.h"

4、将json字符串转为NSDictionary对象

  1. //测试json的解析  
  2. -(void)testJsonParser: (NSString *) jsonString  
  3. {  
  4.     jsonString = [[NSString alloc] initWithString:@"{\"userInfo\":{\"userName\":\"张三\",\"sex\":\"男\"}}"];  
  5.     NSLog(@"正在解析json字符串是:%@",jsonString);  
  6.       
  7.     SBJsonParser * parser = [[SBJsonParser alloc] init];  
  8.     NSError * error = nil;  
  9.     NSMutableDictionary *jsonDic = [parser objectWithString:jsonString error:&error];  
  10.     NSMutableDictionary * dicUserInfo = [jsonDic objectForKey:@"userInfo"];  
  11.       
  12.     NSLog(@"%@",[jsonDic objectForKey:@"userInfo" ]);  
  13.     NSLog(@"%@",[dicUserInfo objectForKey:@"userName"]);  
  14.     NSLog(@"%@",[dicUserInfo objectForKey:@"sex"]);  
  15. }  

5、 处理json对象有多个记录的方法</span>

  1.         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\"}]}"];  
  2.           
  3.         SBJsonParser * parser = [[SBJsonParser alloc] init];  
  4. //        NSLog(@"%@",customerGridJsonString);  
  5.         NSError * error = nil;  
  6.           
  7.         NSMutableDictionary *root = [[NSMutableDictionary alloc] initWithDictionary:[parser objectWithString:customerGridJsonString error:&error]];  
  8.         NSLog(@"%@",root);  
  9.         //注意转换代码  
  10.         SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];  
  11.           
  12.         NSString *jsonString = [jsonWriter stringWithObject:root];  
  13.           
  14.         [jsonWriter release];  
  15.         NSLog(@"%@",jsonString);  
  16.         //注意转换代码  
  17.         NSMutableArray * customers = [root objectForKey:@"customer"];  
  18.         NSLog(@"%@",customers);  
  19.         for(NSMutableDictionary * member  in customers)  
  20.         {  
  21.             NSLog(@"%@",[[member objectForKey:@"name"] description]);  
  22.         }  


6、递归遍历解析出的NSDictionary对象

  1. -(void)visitDict:(NSDictionary *)dict{    
  2.   NSArray *keys=[dict allKeys];    
  3.   for (NSString *key in keys) {    
  4.      NSString *result=[NSString stringWithFormat:@"key=%@,value=%@",key,[dict objectForKey:key]];    
  5.      NSLog(result);    
  6.      if([[dict objectForKey:key] isKindOfClass:[NSDictionary class]]){    
  7.             [self visitDict:[dict objectForKey:key]];    
  8.      }    
  9.    }    
  10. }    

7、将解析出的NSDictionary对象还原为json字符串 
</span>

</div> NSString * jsonStr=[items JSONRepresentation]; </span>