gpt4 book ai didi

ios - JSON Parse iOS Array of Dictionaries 解析成数组只显示 tableview 中的最后一个对象

转载 作者:行者123 更新时间:2023-12-01 18:16:37 25 4
gpt4 key购买 nike

我有一个我正在解析的字典 JSON 数组。我的问题是我想在数组中显示所有符合我所需键值对(键是名称)的记录,我只在我的表格 View 中显示最后一个。几乎是凌晨 4 点,我从晚上 10 点开始一直在转圈,所以任何帮助都会非常感激,因为我忽略了一些东西。谢谢!

NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
self.someArray = [[NSMutableArray alloc]init];

for (NSMutableDictionary *dictionary in jsonDataArray)
{
NSMutableArray* Response_array = [dictionary objectForKey:@"loans"];
NSLog(@"Array: %@", Response_array);

NSDictionary *dict = [Response_array objectAtIndex:0];
NSLog(@"dict is %@",dict);

self.someMutableArray = [dict objectForKey:@"name"];

NSLog(@"what is name %@",self.someMutableArray);
}

我试过了:
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];   

for ( int i = 0 ; i < jsonDataArray.count ; i++ )
{
self.someDictionary = [[jsonDataArray objectAtIndex:i] objectForKey:@"loans"];
self.someMutableArray = [self.someDictionary valueForKey:@"name"];
NSLog(@"MutableArray inside is %@", self.someMutableArray);
}

NSLog(@"MutableArray outside is %@",self.someMutableArray);

在我最后一次尝试中,我移动了 valueForKey:@"name"的位置:
NSArray *jsonDataArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
self.someMutableArray = [NSMutableArray array];


for ( int i = 0 ; i < jsonDataArray.count ; i++ )
{
self.someMutableArray = [[jsonDataArray objectAtIndex:i] objectForKey:@"loans"];
}

NSLog(@"someMutableArray outside is %@",self.someMutableArray);

然后在我的表格 View 的 cellForRowAtIndexPath 中,我有:
NSDictionary *dict2 = [self.someMutableArray objectAtIndex:indexPath.row];
NSLog(@"what is dict2 %@", dict2);
cell.textLabel.text = [dict2 valueForKey:@"name"];

这是我的 JSON 的设置:
[
-{
id: 285,
name: name 1,
-loans: [
-{
id: 42,
name: "Shark"
}
]
},
-{
id: 286,
name: name 2,
-loans: [
-{
id: 50,
name: "Flipper"
}
]
}
]

最佳答案

既然已经有了数组,为什么还要循环呢?只需使用 JSON 响应分配您的数组

NSArray *jsonDataArray = [[NSArray alloc] initWithArray:[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error]];

这个数组将是你的数据源,所以从委托(delegate)和你的 rowAtIndexPath 返回它的计数
NSDictionary *dictObject = [jsonDataArray objectAtIndex:indexPath.row];
cell.textLabel.text = [dictObject valueForKey:@"Shark"];

对于自定义单元格,请喜欢
NSDictionary *dictObject = [jsonDataArray objectAtIndex:indexPath.row];
cell.textLabel1.text = [dictObject valueForKey:@"Shark"];
cell.textLabel2.text = [dictObject valueForKey:@"Flipper"];

关于ios - JSON Parse iOS Array of Dictionaries 解析成数组只显示 tableview 中的最后一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21379929/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com