1

我有以下代码试图解析我从网站返回的 JSON:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

     [connection release];

     NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

     NSLog(@"my ns string = %@", responseString);

     [responseData release];

     NSError *error; 
     NSDictionary *dictionary = [parser objectWithString:responseString   
                                               error:&error]; 
     while (error) { 
         NSLog(@"%@", error); 
         error = [[error userInfo] objectForKey:NSUnderlyingErrorKey]; 
     } 

     NSLog(@"%@", dictionary);


 }

我收到这些错误:

2011-08-01 20:16:47.273 myJSONParser[1040:b603] Connection didReceiveResponse: 
<NSHTTPURLResponse: 0x4e810f0> - application/json
2011-08-01 20:16:47.279 myJSONParser[1040:b603] Connection didReceiveData of length: 117
2011-08-01 20:16:47.359 myJSONParser[1040:b603] my ns string = 
2011-08-01 20:16:47.361 myJSONParser[1040:b603] Error Domain=org.brautaset.SBJsonParser.ErrorDomain Code=0 "Unexpected end of input" UserInfo=0x4eada30 {NSLocalizedDescription=Unexpected end of input}
2011-08-01 20:16:47.363 myJSONParser[1040:b603] (null)

我确实可以控制我正在尝试获取的 JSON,并且在生成 JSON 的 PHP 内部我将标头设置如下:

header("Content-Type:application/json");
...
echo json_encode($arr);

“输入意外结束”让我相信 JSON 格式不正确,但 JSONLint 告诉我它完全有效。我究竟做错了什么?感谢您抽出宝贵时间阅读本文,任何建议将不胜感激!

更新:

我这样设置responseData:

NSMutableData *responseData;

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
         NSLog(@"Connection didReceiveData of length: %u", data.length);

         [responseData appendData:data];

     }

像这样的解析器(在.h中):

SBJsonParser *parser;

和.m:

parser = [[SBJsonParser alloc] init];

查尔斯发现:

HTTP/1.1 200 OK
Date: Tue, 02 Aug 2011 03:30:14 GMT
Server: Apache
X-Powered-By: PHP/5.2.15
Transfer-Encoding: chunked
Content-Type: application/json

[{"key1":"Name","key2":"First","key3":"2011-08-13"},{"key1":"Second","key2":"test2","key3":"2011-08-13"}]

收到的 NSData 说明:

打印数据描述:{length = 117, capacity = 256, bytes = 0x5b7b22686f6d65223a22426c61636b62 ... 30382d3133227d5d}

4

1 回答 1

1

代码中可以看出,当找到 EOF 令牌时,我们只会得到“意外的输入结束”。

SBJsonParser.m:

case SBJsonStreamParserWaitingForData:
            self.error = @"Unexpected end of input";
            break;

SBJsonStreamParserState.m:

- (SBJsonStreamParserStatus)parserShouldReturn:(SBJsonStreamParser*)parser {
    return SBJsonStreamParserWaitingForData;
}

SBJsonStreamParser.m:

    switch (tok) {
        case sbjson_token_eof:
            return [state parserShouldReturn:self];
            break;
    ... }

您的日志似乎表明 NSString 有问题。我会检查响应数据以确保它是正确的——您可以使用像 Fiddler 或 Charles 这样的代理、xcode 调试器或只是普通的旧 NSLog() 来执行此操作。

编辑:

好的,我将您从调试器获得的数据转换为 UTF-8,这就是我得到的:

[{"home":"Blackb ... 08-13"}]

您只粘贴了字节数组的一部分,因此省略号的位置应该更多。'home' 或 'blackb' 对你来说意味着什么吗?查尔斯截获的响应数据中没有任何内容。您是否在 didReceiveReponse 委托方法中对 responseData 执行 setLength:0 ?

于 2011-08-02T02:52:45.817 回答