1

我通过以下方式向服务器发送请求:

- (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 的转换。我调查发现问题是因为有几个外国字符(中文或其他),解析过程出错了。

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

4

1 回答 1

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! :)

}
于 2013-03-19T16:27:55.770 回答