I've been trying unsuccessfully to parse this json:
[{"op":"replace","path":"/pending_coins","value":20}]
I want the value of 20 so I can do
int quantity = jsonValue; //20
Here's what I currently have:
NSArray *patch =[NSJSONSerialization JSONObjectWithData:anEvent.data options:NSJSONReadingMutableContainers error:&e];
NSDictionary *dict = patch[0];
NSLog(@"patch: %@", dict);
NSInteger quantity = (NSInteger)[dict valueForKey:@"value"];
NSLog(@"quantity: %ld",(long)quantity);
if (quantity > 0) {
NSLog(@"You earned %ld coins!",(long)quantity);
}
I've tried both objectForKey
and valueForKey
and neither seems to get me what I'm looking for.
If I do [NSString stringWithFormat:@"%@",[patch valueForKey:@"value"]]
I get a value of 20 as a String, but intValue
and integerValue
on that don't seem to net me what I want.
Right now, the logs show this: quantity: -5764607523034234845
Any ideas where I'm going wrong? I can't control the JSON or I'd just nix the outer array around the object.
An integer in a JSON dictionary will be mapped to an instance of NSNumber
when deserialized, which has various methods on it to retrieve scalar values.
To get an NSInteger
from the JSON you would do:
NSNumber *number = [dict objectForKey:@"value"];
NSInteger quantity = [number integerValue];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.