1

我正在使用 NSJSONSerialization 类来解析以下 JSON 数据,但是,它返回 null。我的 JSONData 前面有标题,“jsonp1343930692(”。有什么办法可以在放入 NSJSONSerialization 之前处理/消除它?

     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 回答