2

JSONタイプのデータに対して非同期リクエストを行うアプリを開発しています。最近、自分のコードに奇妙なバグが見つかりましたが、なぜそれが起こっているのかわかりません。

コードにOK!

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

NSError *error=nil;

    result = [NSJSONSerialization JSONObjectWithData:retrievedData options:kNilOptions error:&error];
        NSLog(@"Result %@",result);
        NSLog(@"Retrieved data %@",retrievedData);
}

結果は NSDictionary で、retrieveData は NSMutableData です。99% の確率で問題なく動作し、connectionDidFinishLoading が呼び出され、結果が入力されます。ただし、その 1% の時間で取得されたデータはデータで満たされていますが、私の結果は null です (写真でわかるように。誰か助けてくれませんか?

ログ

編集:次のエラーが表示されます

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Garbage at end.) UserInfo=0x753e5c0 {NSDebugDescription=Garbage at end.}
4

4 に答える 4

3

最初にエラーを調べて、それが何が悪いのかを示しているかどうかを確認すると役立ちます。

[編集]
あなたのエラーは理由を述べています:Garbage at end.

Webサーバーからの応答は有効なJSONではなく、出力の最後に無効な文字が含まれています。

于 2013-01-24T10:46:29.887 に答える
2

同じ問題がありました。まず、正しく解析されなかったデータを見てください - 私の場合はそうしました

NSString *str = [[NSString alloc] initWithData:retrievedData encoding:NSUTF8StringEncoding];

私の場合、理由は-サーバーがいくつかのsocket.write()を続けて送信した場合-すべてのデータが1つのチャンクで受信された、のように

{first:json}{second:json}..

もちろん、これは 1 つの json として解析できないため、区切り文字を導入し、受信したバッファーを正しいチャンクに分割する必要があります。

于 2013-09-06T08:37:55.840 に答える
1

これは少し遅れていますが、これを行うまでオンラインで何も機能しませんでした:

NSString * dataInString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];

NSRange range = [dataInString rangeOfString:@"}" options:NSBackwardsSearch];

if(range.location != NSNotFound)
    dataInString = [dataInString substringWithRange:NSMakeRange(0,range.location+1)];

それ以来ずっと働いています。

于 2014-08-11T09:42:19.437 に答える
0

I had the same error, the problem was my server was attaching some extra lines to my json response, that would not appear when i will get the response in my browser. Using curl from terminal you can see the actual output. The hack was to truncate the extra characters. with json either you have an array or dictionary. Depending on your json structure, you can use the code (as above answer) but look for the comment in line 2

NSString * str = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
NSRange range = [str rangeOfString:@"}" options:NSBackwardsSearch]; // } for dictionary, ] for array

if(range.location != NSNotFound)
str = [str substringWithRange:NSMakeRange(0,range.location+1)];

once you get your string clean from garbage data, you can convert it to data again.

    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

and now from this data you can get your array or dictionary.

id jsonObject = [NSJSONSerialization
                 JSONObjectWithData:data
                 options:kNilOptions error:&error];  // i used id to be general, you can use array or dictionary structure or later cast this object to as per json
于 2014-11-23T09:00:21.980 に答える