is there a way in objectivec to get exact value type from a json dictionary?
For example, consider this json:
{
"ret": 0,
"state": "Italy",
"lat": 45.46347,
"lon": 9.19404
}
I want to get INT
value for " ret ", NSString
value for " state ", and FLOAT
value for " lat " and " lon ".
I'm using this snippet:
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"sampleJson.json"]];
NSDictionary *dict = [ NSJSONSerialization JSONObjectWithData:data options:0 error:nil ];
id val = [ dict valueForKeyPath:@"lat" ][0];
NSLog(@"%@", [val class] );
but obviously, the output is a generic NSNumber
.
2014-01-31 11:13:51.903 Test0002[2044:70b] __NSCFNumber
It's possible to get a float
instead of NSNumber
, automatically?
To check if the NSNumber is float or int, you can use this method:
if ([val isMemberOfClass:[NSNumber class]])
{
switch(CFNumberGetType((CFNumberRef((NSNumber)val))
{
/* List of results:
kCFNumberSInt8Type
kCFNumberSInt16Type
kCFNumberSInt32Type
kCFNumberSInt64Type
kCFNumberFloat32Type
kCFNumberFloat64Type
kCFNumberCharType
etc... */
}
}
Once you found the type, just use:
float f = [((NSNumber)val) floatValue];
or
int i =[((NSNumber)val) intValue];
Find the whole list here:
To check that it's a NSString, just do:
if([val isMemberOfClass:[NSString class]])
{
}
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.