ObjectForKey, JSON on iOS? Does not work!

I loaded some MySQL data back into the application using the code below, of course, not everything is there, only what is required. I can't seem to appreciate the value of cash, even though JSON from my PHP file has returned successfully. I am 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)
+3
source share
3 answers

Your JSON data contains the array as a top-level object, so you cannot deserialize 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];

, JSON , (). , , . :

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

, !

:

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

two things I would check:

  • Your json is correctly created

  • The encoding you specified is correct.

In particular, I would try to use NSASCIIStringEncoding instead of NSUTF8StringEncoding (I assume that only because it often causes problems, as far as I saw)

0
source

All Articles