当我发送API时,我会得到 JSON 响应。
{" ABC":[{" ID1":"响应"" ID2":"响应" " ID3":"响应"" ID4":"响应"" ID5":"响应"},{" ID1":"响应"" ID2":"响应"" ID3&#34 ;:"响应"" ID4":"响应"" ID5":"响应"},{& #34; ID1":"响应"" ID2":"响应"" ID3":"响应&# 34;," ID4":"响应"" ID5":"响应"}],"状态&#34 ;: "好的","计算":3}
{" XYZ":[{" ID1":"响应"},{" ID1":"响应&# 34;},{" ID1":"响应"}],"状态":" OK""计数&#34 ;: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
。
答案 0 :(得分:1)
获得AB后,其字典数组
您可以轻松使用 valueForKeyPath ,例如:
NSArray * AB = @[@{
@"ID1":@"response",
@"ID2":@"response",
@"ID3":@"response",
@"ID4":@"response",
@"ID5":@"response",
},@{
@"ID1":@"response",
@"ID2":@"response",
@"ID3":@"response",
@"ID4":@"response",
@"ID5":@"response"
}];
NSArray * ID1 = [AB valueForKeyPath:@"ID1"];
NSArray * ID2 = [AB valueForKeyPath:@"ID2"];
答案 1 :(得分:0)
如何一次接收两个JSON对象?
您展示的JSON确实是两个有效的JSON编码连接在一起。如果您的服务器正在执行此操作并且您无法解决问题,那么您可以尝试自行修复它:
][
,}{
,]{
或}[
在两个字符之间有任意数量的空格都是一个JSON编码的结束和开始下一个。构造一个NSRegularExpression
来查找这些序列,并用相同的close / open括号/大括号组合替换它们,但在它们之间加上逗号(,
)。[
,在结尾添加一个]
。这两个步骤会将连接的JSON编码转换为单个编码的JSON数组。现在像往常一样解析和处理,记住你首先需要索引到最外面的数组,以便在索引到索引之前访问特定的JSON响应,以访问你需要的元素。
HTH