如何parsing收到的回复
我对iOS应用程序开发非常陌生,我从服务器获取下面的响应:
"[{\"EmployeeID\":\"000001\",\"EmplyeeName\":\"ABCD EFGHI\"}, {\"EmployeeID\":\"000002\",\"EmplyeeName\":\"ADGHT ASASASAS\"}]"
请有人帮助我如何在我的应用程序中使用员工ID和员工姓名。
你的JSON数据看起来像“嵌套的JSON”,这意味着你必须反序列化两次。
第一个反序列化从你的JSON数据中提取一个string:
NSData *response = ...; // your data NSError *error; NSString *innerJson = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:&error];
现在innerJson
是string
[{"EmployeeID":"000001","EmplyeeName":"ABCD EFGHI"},{"EmployeeID":"000002","EmplyeeName":"ADGHT ASASASAS"}]
这又是JSON数据。 第二个反序列化提取数组:
NSArray *entries = [NSJSONSerialization JSONObjectWithData:[innerJson dataUsingEncoding:NSUTF8StringEncoding] options:0 error:&error];
现在你可以像访问它
for (NSDictionary *entry in entries) { NSString* employeeID = [entry objectForKey:@"EmployeeID"]; NSLog(@"%@", employeeID); }
NSData *response = ...; NSArray *entries = [NSJSONSerialization JSONObjectWithData:response options:0 error:nil]; for(NSDictionary* entry in entries) { NSString* employeeID = [entry objectForKey:@"EmployeeID"]; }
看看JSONparsing器你的回应是JSON,所以你需要从JSON获取数据。
NSURL * url=[NSURL URLWithString:@"<YourURL>"]; NSData * data=[NSData dataWithContentsOfURL:url]; NSError * error; NSMutableDictionary * json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error]; NSLog(@"%@",json); NSMutableArray * EmployeeID=[[NSMutableArray alloc]init]; NSMutableArray * EmployeeName=[[NSMutableArray alloc]init]; NSArray * responseArr = json[@"geonames"]; for(NSDictionary * dict in responseArr) { [EmployeeID addObject:[dict valueForKey:@"EmployeeID"]]; [EmployeeName addObject:[dict valueForKey:@"EmplyeeName"]]; }
现在你得到了EmployeeID,EmployeeName数组,现在你可以在任何你想要的地方使用。
看一眼:
NSJSONSerialization
用这个:
NSData* yourData = [[NSData alloc] initWithContentsOfURL: yourURL]; NSarray* yourJSON = [NSJSONSerialization JSONObjectWithData:yourData options:kNilOptions error:nil];
希望这个帮助你:)
尝试使用这个:
NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];