I am having this weird issue. NSDictionary is not returning the correct integer value.
JSON response code from server.
{
"status":"ok",
"error_code":0,
"data" : [],
"msg":"everything is working!"
}
The JSON is being converted to a NSDictionary.
NSError *error = nil;
NSDictionary *jsonDict = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error: &error];
I access the NSDictionary value using the following code.
int error_code = (int)[jsonDict valueForKey:@"error_code"]
NSLog(@"%i", error_code);
The log outputs the following: 143005344
I've even tried objectForKey and I get the same response.
Thanks, in advance.
Yes it outputs the pointer of the value and that's why you see this log output.
You cannot cast the pointer to an integer and expect the value.
int error_code = [[jsonDict valueForKey:@"error_code"] integerValue];
or if you want to use modern objective-c
int error_code = [jsonDict[@"error_code"] integerValue];
Numbers are stored as NSNumber
instances in plist/json dictionaries. Try calling one of NSNumber
's getters like intValue
:
int error_code = [jsonDict[@"error_code"] intValue];
Note also the new subscripting syntax for dictionaries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With