开发者

How to get the object types with JSONKit

开发者 https://www.devze.com 2023-03-11 18:20 出处:网络
I\'m trying to decoder a json file and get value type for each unknowing the atributes names or the order.

I'm trying to decoder a json file and get value type for each unknowing the atributes names or the order.

Ie.

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

So: Name will be a NString with Klove inside. Latitude a float with 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]]);
    }
}

So... I don't know how could i get the type of the object in the json dictionary. Any idea开发者_StackOverflow社区? If is possible I wouldn't like to make checks like:

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

Thanks in advance.


Ok. My fault.

If I define the JSON file like:

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

instead the above format I'll get the types automatically with the JSONKit.

To get the type in my code:

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

精彩评论

暂无评论...
验证码 换一张
取 消