我试图通过JSON数组进行迭代以获取项密钥和值。
这是我的JSON数组:
{
"ClientData": [{
"Name": "Michael"
}, {
"Last": "Ortiz"
}, {
"Phone": "5555555555"
}, {
"email": "test@gmail.com"
}],
"ClientAccess": [{
"T-Shirt": "YES"
}, {
"Meals": "NO"
}, {
"VIP": "YES"
}, {
"Registration Completed": "Pending"
}]
}
现在,我正在尝试遍历“ClientData”数组,但由于某种原因,该应用程序崩溃时出现此异常:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance
这是我用来迭代JSON数组的代码:
NSDictionary* object = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
// Client Profile Data
NSDictionary *clientDataDict = [object objectForKey:@"ClientData"];
for (id item in clientDataDict)
{
[JSONUserData addObject:[clientDataDict objectForKey:item]];
}
当我没有将JSON数组上的每个项放在数组中时,此代码工作正常。我这样做是为了在阵列上保持连续的顺序。
有人能给我任何关于问题的指示吗?
谢谢!
答案 0 :(得分:2)
ClientData
是一个数组 - 由方括号[]
表示 - 包含分别带有一个键/值对的字典(非常繁琐的结构)。
NSDictionary* object = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];
// Client Profile Data
NSArray *clientDataArray = [object objectForKey:@"ClientData"];
for (NSDictionary *dict in clientDataArray) {
for (NSString *key in dict) {
[JSONUserData addObject:[dict objectForKey:key]];
}
}
答案 1 :(得分:1)
根据您的JSON字符串,看起来ClientData与数组配对,并且数组中的每个项目都是字典。因此,修订后的代码如下:
NSMutableDictionary *mDict = [NSMutableDictionary new];
NSArray *array = [object objectForKey:@"ClientData"];
for (NSDictionary *item in array) {
[mDict addEntriesFromDictionary:item];
}