0

Hi I have the following json that i need to parse, however, I'm struggling to parse the inner array. What I have currently just prints each of the inner arrays but I'd like to print say each title and add the titles to an array. Thank you for any help!

JSON

{"nodes":[{
    "node":{
        "nid":"1420857",
        "title":"Title 1",
        "votes":"182",
        "popular":"True",
        "teaser":"Teaser 1"
    }},
    {"node":{
        "nid":"1186152",
        "title":"Title 2",
        "votes":"140",
        "popular":"True",
        "teaser":"Teaser 2"
    }},
    {"node":{
        "nid":"299856",
        "title":"Title 3",
        "votes":"136",
        "popular":"True",
        "teaser":"Teaser 3"
    }}
]}

Json Parser

    NSError *error = nil;
    NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://www.somefilename.json"]];
    if (jsonData) {
        id jsonObjects = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
        if (error) {
            NSLog(@"error is %@", [error localizedDescription]);
            return;
        }
        NSArray *keys = [jsonObjects allKeys];
        for (NSString *key in keys) {
            NSLog(@"%@", [jsonObjects objectForKey:key]);
        }
    } else {
        // Handle Error
    }
5
  • it works all right, does exactly what is supposed to do. what's the problem? Commented Sep 7, 2012 at 5:55
  • What do you mean by inner array? There is only one array in what you posted, everything else is a dictionary. What exactly is it that you want to parse? Commented Sep 7, 2012 at 5:56
  • Like I need to print say each title in my loop I've tried a lot of things but can't figure how to grab those objects inside what i'm printing. Just edited my question sorry that I wasn't clear but I'd pretty much just like to print each title in my loop rather than each array Commented Sep 7, 2012 at 5:57
  • You HAVE already grabbed them Commented Sep 7, 2012 at 6:00
  • It is NSDictionary --> NSArray --> NSDictionary --> NSDictionary --> NSString. Commented Sep 7, 2012 at 6:00

2 Answers 2

1

Just typecast it:

NSArray *nodes = (NSArray*)[jsonObjects objectForKey:@"nodes"];
for (NSDictionary *node in nodes){
     // do stuff...
}

Methods that return id (like -[objectForKey:], and -[objectAtIndex:]) can return any objective-c object. You'll need to know ahead of time what to typecast it into to perform the appropriate operations on it. JSON is converted to the NSObject equivalents:

  • object -> NSDictionary
  • array -> NSArray
  • string -> NSString
  • number -> NSNumber
  • boolean -> NSNumber
  • float -> NSNumber
  • null -> NSNull

To differentiate between the various NSNumbers, you'll have to call the appropriate type method: -[intValue], -[boolValue], -[floatValue]. Check out the NSNumber docs for more info.

Sign up to request clarification or add additional context in comments.

5 Comments

In the do stuff comment how could i just log the title
I tried NSLog(@"%@",[node objectForKey:@"title"]); however that just gives me null
It's a nested object, so you'll need to do [(NSDictionary *)[node objectForKey:@"node"] objectForKey:@"title"];
Ahh perfect thanks a ton for the help sorry I'm so new to this :)
For numbers take a look at [NSNumberFormatter numberFromString:] it makes your life easy if you're not certain of the format of the numbers, it just parses the string to a number value, you can decide later how you want to use it: int, float, etc.
0

You can use my method for json parsing,

Parse Method:

    -(void)jsonDeserialize:(NSString *)key fromDict:(id)content completionHandler:(void (^) (id parsedData, NSDictionary *fromDict))completionHandler{
    if (key==nil && content ==nil) {
        completionHandler(nil,nil);
    }
    if ([content isKindOfClass:[NSArray class]]) {
        for (NSDictionary *obj in content) {
          [self jsonDeserialize:key fromDict:obj completionHandler:completionHandler];
        }
    }
    if ([content isKindOfClass:[NSDictionary class]]) {
        id result = [content objectForKey:key];
        if ([result isKindOfClass:[NSNull class]] || result == nil) {
            NSDictionary *temp = (NSDictionary *)content;
            NSArray *keys = [temp allKeys];
            for (NSString *ikey in keys) {
             [self jsonDeserialize:key fromDict:[content objectForKey:ikey] completionHandler:completionHandler];
            }
        }else{
            completionHandler(result,content);
        }
    }
}

Method Call:

 NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Sample" ofType:@"json"]];
    NSError *error;

//to get serialized json data...

   id dictionary = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&error];

//get data for key called GetInfo

     [self jsonDeserialize:@"GetInfo" fromDict:dictionary completionHandler:^(id parsedData, NSDictionary *fromDict) {
            NSLog(@"%@ - %@",parsedData,fromDict);
        }];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.