buzzkip
buzzkip

Reputation: 613

objectForKey, JSON in iOS? Not working!

I've fed some MySQL data back to the application by using the code below, of course not everything is there, only what is required. I can't seem to grab the value of 'cash' despite having successfully returned the JSON from my PHP file. I'm using Touch JSON.

Please help?

NSString *urlString = [NSString stringWithFormat:@"http://REMOVED/REMOVED.php?login_key=%@&username=%@",login_key,username];

NSString *strResponse = [self stringWithUrl:[NSURL URLWithString:urlString]];
NSLog(@"%@", strResponse);


NSData *jsonData = [strResponse dataUsingEncoding:NSUTF8StringEncoding];
NSError *error = nil;
NSDictionary *dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error];
NSLog(@"Cash: %@", [dictionary objectForKey:@"cash"]);

This returns the log below:

2011-05-29 10:10:35.493 test1[623:207] [[[{"uid":"0","username":"admin","password":"REMOVED","email":"REMOVED","cash":"925071","exp":"117500","level":"1","clan":"YES","clanid":"1"}]]]

2011-05-29 10:10:35.495 test1[623:207] Cash: (null)

Upvotes: 3

Views: 2695

Answers (3)

sergio
sergio

Reputation: 69047

two things I would check:

  1. Your json is correctly produced

  2. The encoding you specify is the right one.

Specifically, I would try and use NSASCIIStringEncoding instead of NSUTF8StringEncoding (I am suggesting that only because it's often the reason of problems as far as I saw )

Upvotes: 0

user557219
user557219

Reputation:

Your JSON data contains an array as the top-level object, hence you cannot deserialise it as a dictionary:

[
  [
    [
      {
        "cash" : "925071",
        "clan" : "YES",
        "clanid" : "1",
        "email" : "REMOVED",
        "exp" : "117500",
        "level" : "1",
        "password" : "REMOVED",
        "uid" : "0",
        "username" : "admin"
      }
    ]
  ]
]

Try this instead:

NSArray *array = [[CJSONDeserializer deserializer] deserializeAsArray:jsonData
                                                                error:&error];

Also, note that there are three arrays in your JSON data, and only the innermost array contains an object (a dictionary). It’s not clear why there are three nested arrays and what would be the other elements in the arrays, so it’s hard to give a generic parsing solution for your problem. One possibility is:

for (NSArray *innerArray2 in array) {
    for (NSArray *innerArray3 in innerArray2) {
        for (NSDictionary *dictionary in innerArray3) {
            NSString *cash = [dictionary objectForKey:@"cash"];
            NSLog(@"Cash = %@", cash);
        }
    }
}

Upvotes: 4

Julian
Julian

Reputation: 1603

Check that your dictionary isn't nil!

A simple way of doing that would be:

if(!dictionary)NSLog(@"dictionary is nil!");

Upvotes: 1

Related Questions