【问题标题】:Parsing JSON returns NULL iOS解析 JSON 返回 NULL iOS
【发布时间】:2012-07-31 16:27:10
【问题描述】:

我正在尝试解析 JSON 字符串:

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

使用此代码:

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"]);

但不是输出“OK: success”而是输出“OK: (null)” 如果您需要 PHP 脚本,我可以发布它。

【问题讨论】:

    标签: php iphone json null


    【解决方案1】:

    您拥有的字符串不是 JSON... 看起来像 var_dump() 或来自 PHP 的东西。这就是它无法解析的原因。

    您需要在 PHP 端使用json_encode()

    【讨论】:

    • @TheDeveloper,我怀疑任何 API 会故意输出。在我看来,这就像有人在调试代码。
    • @TheDeveloper,这是您为数据提供服务的 PHP 脚本吗?如果是这样,是的,而不是var_dump(),使用json_encode()。如果这是其他人的,请告诉他们以某种标准数据格式输出。我想你可以为var_dump() 的输出编写一个解析器,但你为什么要这样做呢?
    • 你为什么不使用 iOS 的 Json 库?
    • 所以在使用json_encode 后输出为string(59) "{"result":"success","source":"setWorldTime","success":true}"
    • @TheDeveloper,停止使用var_dump(),只输出字符串。如果该字符串在您的 iOS 端日志中,那么是的,您现在做的正确。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多