Web サイトから返される 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 の説明:
データの印刷記述: {長さ = 117、容量 = 256、バイト = 0x5b7b22686f6d65223a22426c61636b62 ... 30382d3133227d5d}