[英]Get correct type value from json dictionary
is there a way in objectivec to get exact value type from a json dictionary? 在Objectivec中有没有办法从json字典中获取确切的值类型 ?
For example, consider this json: 例如,考虑以下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 ". 我想获取“ ret ”的
INT
值,“ state ”的NSString
值,“ lat ”和“ lon ”的FLOAT
值。
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
. 但显然,输出是通用
NSNumber
。
2014-01-31 11:13:51.903 Test0002[2044:70b] __NSCFNumber
2014-01-31 11:13:51.903 Test0002 [2044:70b] __NSCFNumber
It's possible to get a float
instead of NSNumber
, automatically? 有可能会自动获得
float
而不是NSNumber
吗?
To check if the NSNumber is float or int, you can use this method: 要检查NSNumber是float还是int,可以使用以下方法:
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: 要检查它是否为NSString,只需执行以下操作:
if([val isMemberOfClass:[NSString class]])
{
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.