【发布时间】:2013-03-19 15:48:24
【问题描述】:
我正在通过以下方式向服务器发送请求:
- (void) getData
{
NSString *url= @"http://example.com";
NSMutableURLRequest *theRequest= [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
exampleConnection =[[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
}
为此,响应是一个 JSON 文件,我将其解析如下:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Connection did finish loading %@",[connection currentRequest]);
NSDictionary *exampleDictionary = [NSJSONSerialization JSONObjectWithData:receivedData options: NSJSONReadingAllowFragments error:nil];
NSLog(@"%@", exampleDictionary); // which gives me null
}
响应之前运行良好。但是现在它给了我一个空值,这显然是因为某些东西阻碍了从 JSON 到 NSDictionary 的转换。我调查发现问题是因为有几个外来字符(中文什么的),导致解析过程出错。
我不知道如何解决这个问题。有没有人有任何想法?
【问题讨论】:
-
你的 url 返回一个有效的 json 响应吗?
-
是的。我将它粘贴到网络浏览器上,它确实如此。
-
您应该使用
NSJSONSerialization调用的error:参数并显示错误消息。数据的内容也将有助于发现问题,例如NSLog(@"%@", [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding]) -
你能把网址分享给我们吗?
-
对不起,我不认为业主会喜欢这样。 :) 但我确实解决了问题。
标签: ios json nsdictionary nsurlconnection nsdata