0

I'm trying to parse the JSON string:

array(3) {
  ["result"]=>
  string(7) "success"
  ["source"]=>
  string(12) "setWorldTime"
  ["success"]=>
  bool(true)
}

With this code:

SBJsonParser *parser = [[SBJsonParser alloc] init];

    // Prepare URL request to download statuses from Twitter
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost/con.php?m=setWorldTime&a=London,0"]];

    // Perform request and get JSON back as a NSData object
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    // Get JSON as a NSString from NSData response
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    NSLog(json_string);
    // parse the JSON response into an object
    // Here we're using NSArray since we're parsing an array of JSON status objects
    NSDictionary *statuses = [parser objectWithString:json_string error:nil];
    NSLog(@"OK: %@", [[statuses objectForKey:@"array"] objectForKey:@"result"]);

But instead of output 'OK: success' it outputs 'OK: (null)' If you need the PHP script I can post it.

1 Answer 1

2

That string you have is anything but JSON... looks like var_dump() or something from PHP. That's why it can't be parsed.

You need to use json_encode() on your PHP end instead.

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

7 Comments

@TheDeveloper, I doubt any API outputs that intentionally. Looks like someone's debugging code to me.
@TheDeveloper, Is this your PHP script serving the data? If so, yes, rather than var_dump(), use json_encode(). If this is someone else's, tell them to output in some standard data format. I suppose you could write a parser for var_dump()'s output, but why would you want to?
Why are you not using an Json lib for iOS?
So after using json_encode it outputs as string(59) "{"result":"success","source":"setWorldTime","success":true}"
@TheDeveloper, Stop using var_dump() and just output the string. If that string is in your log on the iOS side, then yes, you are now doing it correctly.
|

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.