如何使用JSONKit获取对象类型

时间:2011-06-08 17:37:44

标签: objective-c json

我正在尝试解码json文件并获取每个 unknowing 属性名称或订单的值类型。

{
    "Name": "Klove",
    "Altitude": "100",
    "Latitude": "43.421985",
    "Longitude": "-5.823897"
}

所以:名称将是 NString ,其中包含 Klove 。纬度为43.421985的浮动....

//File initialization
NSString *filePath = [[NSBundle mainBundle] 
                      pathForResource:@"buildings" ofType:@"json"];
NSData *fileContent = [NSData dataWithContentsOfFile:filePath]; 
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSDictionary *dict = [jsonKitDecoder objectWithData:fileContent];
// the party starts 
for (NSDictionary *poi in dict) {
    for (int i = 0; i <= [[poi allKeys]count]-1 ; i++) {

        // Here i'm trying to get the object type (but never with success)
        if([[poi objectForKey:[[poi allKeys]objectAtIndex:i]] 
                                                  isKindOfClass:[NSNumber class]]
               || [[poi objectForKey:[[poi allKeys]objectAtIndex:i]] 
                                                  isKindOfClass:[NSArray class]]
               || [[poi objectForKey:[[poi allKeys]objectAtIndex:i]] 
                                                  isKindOfClass:[NSDictionary class]])
        {
            NSLog(@"Other kind of class detected");
            // do somthing but never happens
           // in fact, if i use [[poi objectForKey:[[poi allKeys]objectAtIndex:i]class]
           // always is __NSCFString
        }

        NSLog(@"%@",[[poi allKeys]objectAtIndex:i]);
        NSLog(@"%@",[poi objectForKey:[[poi allKeys]objectAtIndex:i]]);
    }
}

所以...我不知道 我怎样才能获得json字典中对象的类型 。任何的想法?如果可能的话,我不想做像这样的检查:

if ([poi allKeys]objectAtIndex:i] isEqualToString(@"Latitude"))  
    [[poi objectForKey:i]floatValue];

提前致谢。

1 个答案:

答案 0 :(得分:0)

确定。我的错。

如果我将JSON文件定义为:

    {
      "Name": "Klove",
      "Altitude": 100,
      "Latitude": 43.421985,
      "Longitude": -5.823897
     }

而不是上面的格式我将使用JSONKit自动获取类型。

要获取我的代码中的类型:

    [poi objectForKey:[[poi allKeys]objectAtIndex:i]]