如何解析收到的回复

时间:2013-11-08 12:22:55

标签: ios json

我是iOS应用程序开发的新手,我从服务器得到以下响应:

"[{\"EmployeeID\":\"000001\",\"EmplyeeName\":\"ABCD EFGHI\"},
{\"EmployeeID\":\"000002\",\"EmplyeeName\":\"ADGHT ASASASAS\"}]"

请有人帮助我了解如何在我的申请中使用员工ID和员工姓名。

6 个答案:

答案 0 :(得分:2)

NSData *response = ...;
NSArray *entries = [NSJSONSerialization JSONObjectWithData:response
                                                   options:0
                                                     error:nil];

for(NSDictionary* entry in entries) {
    NSString* employeeID = [entry objectForKey:@"EmployeeID"];
}

答案 1 :(得分:2)

您的JSON数据看起来像“嵌套JSON”,这意味着您必须将其反序列化两次。

第一个反序列化从JSON数据中提取字符串:

NSData *response = ...; // your data
NSError *error;
NSString *innerJson = [NSJSONSerialization JSONObjectWithData:response
                              options:NSJSONReadingAllowFragments error:&error];

现在innerJson是字符串

[{"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);
}

答案 2 :(得分:1)

查看JSON Parser您的响应是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数组,现在您可以在任何地方使用它。

答案 3 :(得分:0)

答案 4 :(得分:0)

使用此:

NSData* yourData = [[NSData alloc] initWithContentsOfURL: yourURL];
NSarray* yourJSON = [NSJSONSerialization JSONObjectWithData:yourData options:kNilOptions error:nil];

希望这可以帮助你:)

答案 5 :(得分:0)

尝试使用它:

NSDictionary *myJSON = [NSJSONSerialization JSONObjectWithData:myData options:NSJSONReadingMutableContainers error:nil];
相关问题