我正在使用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);
}
答案 0 :(得分: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
}
}
答案 1 :(得分: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];
希望这有帮助!