NSJSONSerialization不起作用,NSUTF8StringEncoding正在工作

时间:2014-03-11 12:50:24

标签: ios json nsdata nsjsonserialization

我已经阅读了文档,教程和其他Stack Q& A,我很想知道如何使用JSON显示NSUTF8StringEncoding,但不能使用{{ 1}} - 我需要将数据提取到NSJSONSerializationNSDictionary。我认为从我的网址返回NSArray格式是个问题吗?

编辑这是错误:错误Domain = NSCocoaErrorDomain Code = 3840“操作无法完成。(Cocoa error 3840。)”(垃圾结束。)UserInfo = 0x8aabc30

NSData

调试控制台:

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.sampleURL.com"]
                                          cachePolicy:NSURLRequestUseProtocolCachePolicy
                                      timeoutInterval:15.0];

NSMutableData* responseData = [NSMutableData dataWithCapacity: 0];

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    //this works, and have NSLog below
    responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"string %@", responseString);

    [responseData appendData:data];
    responseData = [[NSMutableData alloc] initWithData:data];

     //this is null in NSLog
    NSError * error;
    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data   options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&error];

    NSLog(@"jsonDict dict %@",jsonDict); 
}

4 个答案:

答案 0 :(得分:4)

您已经在' didReceiveData'中完成了所有操作。委托功能不是正确的地方。唯一应该存在的是:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [self.responseData appendData:data];
}

但在此之前,您应该初始化' self.responseData'当连接收到响应时:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if(self.responseData != nil) self.responseData = nil;
    self.responseData = [[NSMutableData alloc] init];
}

然后,您需要实现另一个名为' connectionDidFinishLoading'的委托函数。当调用此方法时,您的响应数据'将包含来自JSON的所有数据,并准备解析:

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

     responseString = [[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding];

     NSLog(@"string %@", responseString);

     NSError * error;
     NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingAllowFragments error:&error];

     NSLog(@"jsonDict dict %@",jsonDict); 
}

我希望在某种程度上有所帮助。

答案 1 :(得分:3)

您的JSON格式不正确。你告诉我们它是(为了易读性而添加了空格和换行符):

{
    "id": "a1",
    "session": "General",
    "name": "Exhibitor Setup Begins",
    "startTime": "0900",
    "details": "9am Exhibitor Hall",
    "png": "image",
    "speaker1": "Johnson",
    "speaker2": "Nelson",
    "speaker3": ""
}{
    "id": "b1",
    "session": "General",
    "name": "Conference Registration",
    "startTime": "1000",
    "details": "10am Noon Upper Level Lobby",
    "png": "image",
    "speaker1": "Jackson",
    "speaker2": "",
    "speaker3": ""
}

这两个字典条目之间缺少一个逗号,你错过了应该包装JSON的[]。如果它确实是一个字典条目数组,它应该是:

[
    {
        "id": "a1",
        "session": "General",
        "name": "Exhibitor Setup Begins",
        "startTime": "0900",
        "details": "9am Exhibitor Hall",
        "png": "image",
        "speaker1": "Johnson",
        "speaker2": "Nelson",
        "speaker3": ""
    },
    {
        "id": "b1",
        "session": "General",
        "name": "Conference Registration",
        "startTime": "1000",
        "details": "10am Noon Upper Level Lobby",
        "png": "image",
        "speaker1": "Jackson",
        "speaker2": "",
        "speaker3": ""
    }
]

如果您想查看JSON,可以访问http://jsonlint.com。此外,如果您选中error返回的JSONObjectWithData对象,则会指向正确的方向。

您应该了解如何生成此JSON。看起来它必须是手动生成的。例如,如果您是从PHP页面生成的,则应使用json_encode,而不是手动生成JSON。


顺便说一句,您正试图在didReceiveData中解析结果。在connectionDidFinishLoading之前,您不应该尝试解析。您的didReceiveData应该仅将data附加到您的NSMutableData对象。解析应该推迟到connectionDidFinishLoading

答案 2 :(得分:0)

嗨,你可以试试这个。

NSError *error = nil;
NSArray *jsonResponseArray = [NSJSONSerialization JSONObjectWithData: YOURDATA options: NSJSONReadingMutableContainers error: &error];

if (!jsonResponseArray) {
  NSLog(@"Error: %@", error);
} else {
   for(NSDictionary *dic in jsonResponseArray) {
      NSLog(@"dic values are : %@", item);
   }
}

由于

答案 3 :(得分:0)

您发布的JSON字符串不是有效的JSON。仅仅因为数据是有效的UTF8字符串并不意味着它必然是JSON。尝试将调试后的字符串粘贴到JSONLint,它会显示您在JSON对象之间缺少逗号。