我遇到了分离如何处理两个JSOn响应的问题。如果只返回一个元素,它会给出不同于两个的响应:
这是一个结果:
{
"voteMap": {
"SID": "2727",
"CNT": "1",
"VTD": "N"
}
}
还有两个:
{
"voteMap": [
{
"SID": "2814",
"CNT": "1",
"VTD": "N"
},
{
"SID": "2815",
"CNT": "1",
"VTD": "N"
}
]
}
我从拥有一个数组到拥有一系列字典。以下是我处理它的方式:
responseArr = jsonArray[@"voteMap"];
if([jsonArray count] == 1){
Song* song = [self findSong:[responseArr valueForKey:@"SID"]];
song.votes =[responseArr valueForKey:@"CNT"];
song.status = [responseArr valueForKey:@"VTD"];
}
else{
for (NSDictionary *dict in responseArr) {
Song *song = [self findSong:[dict valueForKey:@"SID"]];
song.votes =[dict valueForKey:@"CNT"];
song.status = [dict valueForKey:@"VTD"];
}
}
抱歉格式不正确。发生的事情是[jsonArray count] == 1
总是在发生......因为它总是返回voteMap
答案 0 :(得分:1)
我建议用这样的方式检查类型:
id object = [response objectForKey:@"voteMap"];
if ([object isKindOfClass:[NSArray class]]) {
// process multible objects
} else if ([object isKindOfClass:[NSDictionary class]]) {
// process individual object
}
答案 1 :(得分:1)
responseArr = jsonArray[@"voteMap"];
if ([responseArr isKindOfClass:[NSArray class]]) {
for (NSDictionary *dict in responseArr) {
Song *song = [self findSong:[dict valueForKey:@"SID"]];
song.votes =[dict valueForKey:@"CNT"];
song.status = [dict valueForKey:@"VTD"];
}
}
if ([responseArr isKindOfClass:[NSDictionary class]]) {
Song* song = [self findSong:[responseArr valueForKey:@"SID"]];
song.votes =[responseArr valueForKey:@"CNT"];
song.status = [responseArr valueForKey:@"VTD"];
}
}
我认为这会对你有所帮助。
答案 2 :(得分:1)
您可以使用isKindOfClass
方法确定它是NSArray
或NSDictionary
。
答案 3 :(得分:1)
尝试以下代码。并检查json是数组还是字典
id jsonArray;
if([jsonArray isKindOfClass:[NSArray class]]){
Song* song = [self findSong:[responseArr valueForKey:@"SID"]];
song.votes =[responseArr valueForKey:@"CNT"];
song.status = [responseArr valueForKey:@"VTD"];
}
else{
for (NSDictionary *dict in responseArr) {
Song *song = [self findSong:[dict valueForKey:@"SID"]];
song.votes =[dict valueForKey:@"CNT"];
song.status = [dict valueForKey:@"VTD"];
}
}
答案 4 :(得分:1)
NSArray* responseArr = [response objectForKey:@"voteMap"];
if ([responseArr isKindOfClass:[NSDictionary class]]) {
responseArr = [NSArray arrayWithObject:responseArr];
}
for (NSDictionary *dict in responseArr) {
Song *song = [self findSong:[dict valueForKey:@"SID"]];
song.votes =[dict valueForKey:@"CNT"];
song.status = [dict valueForKey:@"VTD"];
}
(我已多次使用过这个模型。)