从URL解析JSON响应会给出<null> </null>

时间:2013-03-19 15:48:25

标签: ios json nsdictionary nsurlconnection nsdata

我正以下列方式向服务器发送请求:

- (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

}

之前的反应很好。但现在它给了我一个null,这显然是因为某些东西阻碍了从JSON到NSDictionary的转换。我调查并发现问题是因为有几个外来字符(中文或其他),解析过程出错了。

我不知道如何解决这个问题。有没有人有任何想法?

1 个答案:

答案 0 :(得分:1)

我玩了类和编码选项,最后做了以下操作,解决了这个问题。

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

    NSLog(@"Connection did finish loading %@",[connection currentRequest]);

    NSString *res = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];

    NSDictionary *exampleDictionary = [NSJSONSerialization JSONObjectWithData:[res dataUsingEncoding:NSUTF8StringEncoding] options: NSJSONReadingAllowFragments error:nil];

    NSLog(@"%@", exampleDictionary); // gives the actual data! :)

}