【发布时间】:2017-08-29 05:13:15
【问题描述】:
当我发送 API 时,我会收到这样的 JSON 响应。
{"ABC":[{"ID1":"response","ID2":"response","ID3":"response","ID4":"response","ID5":"response"} ,{"ID1":"response","ID2":"response","ID3":"response","ID4":"response","ID5":"response"},{"ID1":"response ","ID2":"response","ID3":"response","ID4":"response","ID5":"response"}],"status":"OK","count":3}
{"XYZ":[{"id1":"response"},{"id1":"response"},{"id1":"response"}],"status":"OK","count ":3}
我在响应中得到 两个 JSON 对象。如何将这些数据存储在 MutableArrays 中。
我的代码是...
//Getting data from server through JSON approach ...
self.urlSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
self.urlReq= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:[[NSString alloc] initWithFormat:@"http://MyApiName"]]];
self.dataTask = [self.urlSession dataTaskWithRequest:self.urlReq completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!(data == nil)) {
self.loginDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(@"data : %@", data);
NSLog(@"Login Dic : %@", [self.loginDic objectForKey:@"ABC"]);
if (!(self.loginDic == nil)) {
self.integer = [[self.loginDic objectForKey:@"ABC"] count];
if ([[self.loginDic objectForKey:@"status"] isEqualToString:@"OK"] && (!(self.integer == 0))) {
self.ID1 = [[NSMutableArray alloc]init];
self.ID2 = [[NSMutableArray alloc]init];
self.ID3 = [[NSMutableArray alloc]init];
self.ID4 = [[NSMutableArray alloc]init];
self.ID5 = [[NSMutableArray alloc]init];
for (int i=0; i<self.integer; i++) {
[self.ID1 addObject:[[[self.loginDic objectForKey:@"ABC"] objectAtIndex:i] objectForKey:@"ID1"]];
[self.ID2 addObject:[[[self.loginDic objectForKey:@"ABC"] objectAtIndex:i] objectForKey:@"ID2"]];
[self.ID3 addObject:[[[self.loginDic objectForKey:@"ABC"] objectAtIndex:i] objectForKey:@"ID3"]];
[self.ID4 addObject:[[[self.loginDic objectForKey:@"ABC"] objectAtIndex:i] objectForKey:@"ID4"]];
[self.ID5 addObject:[[[self.loginDic objectForKey:@"ABC"] objectAtIndex:i] objectForKey:@"ID5"]];
}
NSLog(@"%@", self.ID1);
NSLog(@"%@", self.ID2);
} else {
}
} else {
}
} else {
}
}];
[self.dataTask resume];
}
我正在获取数据,但我正在获取loginDic = null。
【问题讨论】:
-
首先,您发布的 JSON 不是有效的。第二件事是您的代码没有任何意义,因为您的 JSON 中的键和代码中的键不同。
-
你是从服务器这样发送的吗?
-
@Midhun MP 很抱歉我编辑了上面的代码...
-
@iOSDeveloper:你能更新一下 JSON 吗?它仍然无效(您可以在此处验证您的 JSON:jsoneditoronline.org)。但是如果你从这样的服务器获取结果,这就是你在解析 JSON 时得到 null 的原因。
-
我遇到了错误。是的,谢谢你...
标签: ios objective-c json web-services