1

NSJSONSerialization クラスを使用して次の JSON データを解析していますが、null が返されます。JSONData の前に「jsonp1343930692(」というヘッダーがあります。

     jsonp1343930692("snapshot":[{"timestamp":1349143800,"data":[{"label_id":10,"lat":29.7161,"lng":-95.3906,"attr":{"ozone_level":37,"exp":"IN","gridpoint":"29.72:-95.39"}},{"label_id":10,"lat":30.168456,"lng":-95.50448}]}]})

また、スナップショットを提供するだけでコードをここに配置しています。

(void) httpRequest
{
url1=[NSURL URLWithString: url];
_weak ASIHTTPRequest *request1=[ASIHTTPRequest requestWithURL:url1];
[request1 setCompletionBlock:^{
   requestData=[request1 responseData];
   [self parsing];

 }];

}

(void) parsing
{
    NSError myError =nil;
    NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:requestData     options:NSJSONMutableLeaves error:&myError];

NSLog(@"%@",dic);

}
4

2 に答える 2

1

ブラウザから試しているのでうまくいくかわかりません。

-(void) parsing
{
    NSString *responseString = [[NSString alloc] initWithData:requestData
                                                     encoding:NSUTF8StringEncoding];
    // you gotta extract a valid JSON format
    // this is not very clean code, You need to depend on what your server responds
    // and fail gracefully
    // I'm assuming that your json data will always be between ()
    // NOTE: in your question you're missing a '{' at the begining of your json to be valid
    NSData *data = nil;
    NSRange *range = [responseString rangeOfString:@"("];
    if (range.location != NSNotFound && range.location < responseString.length) {
        responseString = [responseString substringFromIndex:range.location + 1];
        responseString = [responseString substringToIndex:responseString.length -1];
        data = [responseString dataUsingEncoding:NSUTF8StringEncoding];
    }
    if (data) {
        NSError myError =nil;
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data     
                                                          options:NSJSONMutableLeaves
                                                            error:&myError];
        if(!error) {
            NSLog(@"%@", dic);
        } else {
            //Serialization error
            NSLog(@"%@", error);
        }
    } else {
        //something went wrong with json data extraction
        // fail gracefully
    }
}
于 2012-10-08T22:00:33.743 に答える
1

これは機能するはずであり、最初の括弧で停止することも保証されています。

NSScanner *scanner = [NSSccaner scannerWithString:JSONPString];
[scanner scanUpToString:@"(" intoString:NULL]; //This gets rid of the jsonpNNNNN
NSString *JSONWrappedInParens = [[scanner string] substringFromIndex:[scanner scanLocation]]; //Now we have our JSON wrapped in parentheses
NSCharacterSet *parens = [NSCharacterSet characterSetWithCharactersInString:@"()"]; //trim the parentheses leaving all internal parens untouched.
NSString *justJSON = [JSONWrappedInParens stringByTrimmingCharactersInSet:parens];

お役に立てれば!

于 2012-10-08T23:54:54.197 に答える