我真的不知道这是不是重复的帖子,但我真的不知道如何找到我正在搜索的内容。 我有一个来自json的数据,这个数据的格式是这样的:
{
Age = (
"15",
"23",
"44"
),
Name = (
"Jack",
"Mark",
"Steve"
),
City = (
"New York",
"Los Angeles",
"Miami"
);
}
我需要有关Dictionary风格的数据,如下所示:
{
Age = 15;
Name = Jack;
City = New York;
},
{
Age = 23;
Name = Mark;
City = Los Angeles;
},
{
Age = 44;
Name = Steve;
City = Miami;
};
我使用此代码从json Data:
创建NSDictionaryNSArray *jsonResponse = [responseObject objectForKey:@"Age"];
NSMutableDictionary *allKeys = [NSMutableDictionary dictionary];
for (int i = 0; i < [jsonResponse count]; ++i)
{
NSArray *jsonAge = [[responseObject objectForKey:@"Age"]objectAtIndex:i];
NSArray *jsonName = [[responseObject objectForKey:@"Name"]objectAtIndex:i];
NSArray *jsonCity = [[responseObject objectForKey:@"City"]objectAtIndex:i];
[allKeys setObject:jsonAge forKey:@"Age"];
[allKeys setObject:jsonName forKey:@"Name"];
[allKeys setObject:jsonCity forKey:@"City"];
}
我按照预期得到了这个结果:
(
{
Age = 15;
Name = Jack;
City = New York;
}
)
问题是,我需要所有数据连续,这个提议给我分组在一个简单的组中。 我怎么能在这样的一个团体中得到整个团体?
{
Age = 15;
Name = Jack;
City = New York;
},
{
Age = 23;
Name = Mark;
City = Los Angeles;
},
{
Age = 44;
Name = Steve;
City = Miami;
};
一些建议非常有用,非常感谢!!!!
答案 0 :(得分:0)
更好的解决方案是在解析JSON对象后创建模型类并设置值。模型类将简化您在代码中的其他位置管理/修改数据的方式。
@interface Person : NSObject
@property (nonatomic, strong) NSString *age;
@property (nonatomic, strong) NSString *name;
@property (nonatomic, strong) NSString *city;
@end
然后,您可以解析数据并将它们存储在Person
个对象的数组中。
NSArray *ageArray = [responseObject objectForKey:@"Age"];
NSArray *nameArray = [responseObject objectForKey:@"Name"];
NSArray *cityArray = [responseObject objectForKey:@"City"];
NSMutableArray *personArray = [NSMutableArray new];
for (int i = 0; i < ageArray.count; i++) {
Person *person = [Person new];
person.age = [ageArray objectAtIndex: i];
person.name = (i < nameArray.count) ? [nameArray objectAtIndex: i] : nil;
person.city = (i < cityArray.count) ? [cityArray objectAtIndex: i] : nil;
[personArray addObject: person];
}
注意:如果可以修改JSON服务器响应以表示多个Person
对象而不是单个属性的数组,则应该更新它。