JSON-Framework를 사용하여 Xcode에서 JSON 객체 / JSON 배열을 탐지하는 방법
-
17-09-2020 - |
문제
JSON 구문 분석에 문제가 있습니다.URL을 누르면 JSON 응답이 다음과 같습니다.
//JSON 1
{ "data":
{"array":
["3",
{"array":
[
{"id":"1","message":"Hello","sender":"inot"},
{"id":"2","message":"World","sender":"inot"},
{"id":"3","message":"Hi","sender":"marza"}
]
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
.
그러나 데이터 결과가 1 일 경우 JSON 응답은 다음과 같습니다.
//JSON 2
{ "data":
{"array":
["3",
{"array":
{"id":"3","message":"Hi","sender":"marza"}
}
]
},
"message":"MSG0001:Success",
"status":"OK"
}
.
ID, 메시지 및 보낸 사람 가치를 얻으려면이 코드를 구현하며 JSON 1에서 잘 작동하지만 JSON 2.에서 오류가 발생했습니다. JSON 프레임 워크를 사용합니다.그리고 질문은 JSON 응답이 object ({}) 또는 배열 ([]) 인 것을 감지하는 방법입니다 ([] ??
// Parse the string into JSON
NSDictionary *json = [myString JSONValue];
// Get all object
NSArray *items = [json valueForKeyPath:@"data.array"];
NSArray *array1 = [[items objectAtIndex:1] objectForKey:@"array"];
NSEnumerator *enumerator = [array1 objectEnumerator];
NSDictionary* item;
while (item = (NSDictionary*)[enumerator nextObject]) {
NSLog(@"id = %@",[item objectForKey:@"id"]);
NSLog(@"message = %@",[item objectForKey:@"message"]);
NSLog(@"sender = %@",[item objectForKey:@"sender"]);
}
. 해결책
id
를 사용하고 얻은 개체가 nsarray 또는 nsdictionary인지 확인하십시오.
id item = [json valueForKeyPath:@"data.array"];
if ([item isKindOfClass:[NSArray class]]) {
// item is an array
}
else if ([item isKindOfClass:[NSDictionary class]]) {
// item is a dictionary
}
. 제휴하지 않습니다 StackOverflow