Reputation: 3739
I'm trying to use NSJSONSerialization for retrieving JSON data, the problem is that I can not parse correctly the NSDictionary.
The webservice returns the following:
[{"Status":"No variables"}]
My code looks like this:
...
NSURL * url = [NSURL URLWithString:@"http://justforexamplepurposes.xyz/file.php"];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:[[NSString stringWithFormat:@"username=%@&password=%@", username, password] dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse * response = nil;
NSError * error = nil;
NSData * result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if(error == nil && result != nil)
{
NSError * json_error = nil;
id id_json_serialization = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers error:&json_error];
if(json_error == nil)
{
NSDictionary * dictionary_result = (NSDictionary *) id_json_serialization;
NSLog(@"|>%@<|", dictionary_result);
NSEnumerator * enume;
id key;
enume = [dictionary_result keyEnumerator];
while((key =[enume nextObject]))
{
NSLog(@"%@ : %@", key, [dictionary_result objectForKey:key]);
}
}
}
...
The first NSLog is printed correctly:
|>( { Status = "No variables"; } )<|
But at the second NSLog, it throws an Exception:
2012-03-17 13:57:22.195 TESTAPP[41072:f803] -[__NSArrayM keyEnumerator]: unrecognized selector sent to instance 0x689a9f0 2012-03-17 13:57:22.196 TESTAPP[41072:f803] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSArrayM keyEnumerator]: unrecognized selector sent to instance 0x689a9f0' * First throw call stack: (0x13e9022 0x157acd6 0x13eacbd 0x134fed0 0x134fcb2 0x2a80 0x13eae99 0x3614e 0x360e6 0xdcade 0xdcfa7 0xdc266 0x5b3c0 0x5b5e6 0x41dc4 0x35634 0x12d3ef5 0x13bd195 0x1321ff2 0x13208da 0x131fd84 0x131fc9b 0x12d27d8 0x12d288a 0x33626 0x232d 0x2295) terminate called throwing an exception(lldb)
Any suggestions?
Upvotes: 0
Views: 1342
Reputation: 16448
The JSON that the server is returning actually an array with just one object in it. So your variable dictionary_result
is actually an NSMutableArray.
Quick tip: if you use CFShow(dictionary_result)
rather than NSLog(@"|>%@<|", dictionary_result);
, you might have spotted this, as CFShow gives you a lot more information about your object, including type.
Upvotes: 2