【问题标题】:How to get the object types with JSONKit如何使用 JSONKit 获取对象类型
【发布时间】:2011-06-08 17:37:43
【问题描述】:

我正在尝试解码一个 json 文件并获取每个不知道属性名称或顺序的值类型。

即。

{
    "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];

提前致谢。

【问题讨论】:

    标签: objective-c json


    【解决方案1】:

    好的。我的错。

    如果我像这样定义 JSON 文件:

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

    代替上述格式,我将使用 JSONKit 自动获取类型。

    在我的代码中获取类型:

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

    【讨论】:

      猜你喜欢
      • 2014-01-07
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 2014-01-06
      • 1970-01-01
      • 2019-02-26
      相关资源
      最近更新 更多