【问题标题】:iOS JSON Parse not working (returns null dictionary)iOS JSON Parse 不工作(返回空字典)
【发布时间】:2012-08-17 18:19:24
【问题描述】:

我使用NSJSONSerialization 的JSONObjectWithData:data options: error: 来解析从服务器返回的JSON 数据。

现在对于我使用的选项参数:NSJSONReadingAllowFragments。您可以在下面查看实际的 JSON(我认为问题出在哪里)。

我得到的错误信息是:

Error Domain=NSCocoaErrorDomain Code=3840 “操作无法完成。(Cocoa 错误 3840。)”(字符 0 周围的值无效。) UserInfo=0x6895da0 {NSDebugDescription=字符 0 周围的值无效。}

知道怎么解决吗?

JSON =

{"name":"Johan Appleseed",
"email":"j.appleseed@emuze.co",
"phone":"+4121876003",
"accounts":{
    "facebook":[true,1125],
    "twitter":[false,null],
    "homepage":[true,"http:\/\/johnAplleseed.com\/index.html"]}}

【问题讨论】:

标签: ios json parsing nsjsonserialization


【解决方案1】:

我有一段时间遇到同样的问题,我只是想如果我从网页中提取数据,比如说 PHP 页面,那么该页面中不应该有任何 HTML 标记。所以像这样的结构:

<html>
<body>
<?php

?>
</body>
</html>

会毁了你的结果。把它变成:

<?php

?> 

为我工作。

【讨论】:

    【解决方案2】:

    您也可以在ios中按块点击json数据的url

     #define kBgQueue dispatch_get_global_queue(
     DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) //1
    #define kLatestKivaLoansURL [NSURL URLWithString: 
     @"http://api.kivaws.org/v1/loans/search.json?status=fundraising"] //2
    

    我们需要做的第一件事是从网上下载 JSON 数据。幸运的是,使用 GCD,我们可以在一行代码中做到这一点!将以下内容添加到 ViewController.m:

    - (void)viewDidLoad
    {
    [super viewDidLoad];
    
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: 
          kLatestKivaLoansURL];
        [self performSelectorOnMainThread:@selector(fetchedData:) 
          withObject:data waitUntilDone:YES];
    });
    }
    - (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSError* error;
    NSDictionary* json = [NSJSONSerialization 
        JSONObjectWithData:responseData //1
    
        options:kNilOptions 
        error:&error];
    
    NSArray* latestLoans = [json objectForKey:@"loans"]; //2
    
    NSLog(@"loans: %@", latestLoans); //3
    }
    

    【讨论】:

      【解决方案3】:

      有一种方法,你可以通过post请求解析jsondata

       -(void)callWebserviceList
       {
      spinner.hidden=NO;
      
      NSString *bodyData = @"code_request=monuments_list&asi_id=1";
      
      NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:[NSURL   URLWithString:@"http://asicircles.com/server_sync.php"]];
      
      // Set the request's content type to application/x-www-form-urlencoded
      [postRequest setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
      
      // Designate the request a POST request and specify its body data
      [postRequest setHTTPMethod:@"POST"];
      [postRequest setHTTPBody:[NSData dataWithBytes:[bodyData UTF8String] length:strlen([bodyData UTF8String])]];
      

      connection1 = [NSURLConnection connectionWithRequest:postRequest delegate:self];

      if(connection1 !=nil)
      {
          ////NSLog(@"%@",postRequest);
      }
      

      }

      - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
      
      if ([connection isEqual:connection1 ])
      {
           [responseData setLength:0];
      
      }else if ([connection isEqual:connection2 ])
      {
           [responseData1 setLength:0];
      }
      

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

          if ([connection isEqual:connection1 ])
        {
          [responseData appendData:data];
      
      }else if ([connection isEqual:connection2 ])
      {
           [responseData1 appendData:data];
      }
      
      
      //**check here for responseData & also data**
      

      }

      - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
      {
      NSLog(@"%@",[NSString stringWithFormat:@"Connection failed: %@", [error description]]);
      }
      
      - (void)connectionDidFinishLoading:(NSURLConnection *)connection
      {
      if ([connection isEqual:connection1 ])
      {
          spinner.hidden=YES;
          NSError *error;
      
          NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
      
          NSMutableArray *arrdata=[json objectForKey:@"message"];
          NSLog(@"code is%@", json);
      
          for (int i=0; i< arrdata.count; i++)
          {
              [arrDetails addObject:[[arrdata objectAtIndex:i]objectForKey:@"details"]];
              [arrImageUrl addObject:[[arrdata objectAtIndex:i]objectForKey:@"image"]];
              [arrLat addObject:[[arrdata objectAtIndex:i]objectForKey:@"lat"]];
              [arrLongi addObject:[[arrdata objectAtIndex:i]objectForKey:@"longi"]];
              [arrName addObject:[[arrdata objectAtIndex:i]objectForKey:@"name"]];
              [arrLoc addObject:[[arrdata objectAtIndex:i]objectForKey:@"location"]];
              [arrID addObject:[[arrdata objectAtIndex:i]objectForKey:@"id"]];
      
              NSLog(@"code is%@",[[arrdata objectAtIndex:i]objectForKey:@"details"]);
              NSLog(@"code is%@",[arrImageUrl objectAtIndex:i]);
      
          }
      
      
      
          if (arrName.count > 0)
          {
              [self addscrollView];
          }
      
      
      
      }else if ([connection isEqual:connection2 ])
      {
      
      }
      
      
      }
      

      【讨论】:

        【解决方案4】:

        已经有一段时间了,但打印数据的一种更简单的方法是:

        NSLog(@"%@", [[NSString alloc] initWithData:data 编码:NSUTF8StringEncoding]);

        【讨论】:

          【解决方案5】:

          可能您有一些看不到的无法打印的字符。试试这个:

          NSData *jsonData = ...
          const unsigned char *ptr = [data bytes];
          
          for(int i=0; i<[data length]; ++i) {
            unsigned char c = *ptr++;
            NSLog(@"char=%c hex=%x", c, c);
          }
          

          验证您在数据的开头或结尾没有不可打印的字符。

          编辑:澄清一下,只需在您的 JSON 字典上运行上述内容 - 无法解析的字典。

          【讨论】:

          • 好吧,我运行它,在日志中我得到了一个 html 页面的所有字符(打开和关闭 html、head 和 body 标签),整个 JSON 响应在 body 部分(似乎合法)... 现在可以吗?我应该寻找什么特别的东西吗?
          • 您应该在我的代码中寻找的是非 ascii 字符(严格来说是非 UTF-8 字符)。由于前导 0 或其他小的十六进制值,许多人遇到了您的问题。您向我们展示了上面的示例 - 如果您有来自真实页面的类似的一小部分代码,请将其发布。我唯一不习惯看到的是“\”字符,但我无法想象这是隐藏在字符串中的问题。
          • 生成 JSON 我只需创建一个数组(全部在 PHP 中)并使用 PHP JSON ENCODE 方法将其转换为 JSON 响应....您可以在 @987654321 上查看实际代码@
          • 这真的很有帮助。现在我可以简单地看到导致此特定错误的字符和消息。
          【解决方案6】:

          我确实发现问题在于从 URL 返回的是一个 HTML 页面,在实际响应周围有所有这些 html、head 和 body 标签,因此无法解析。这是关于如何从响应中删除 HTML 标记的一个很好的问答(在它被更改为字符串之后):Remove HTML Tags from an NSString on the iPhone

          【讨论】:

            猜你喜欢
            • 2016-03-14
            • 1970-01-01
            • 2021-07-17
            • 2021-06-29
            • 2016-07-23
            • 2021-04-22
            • 1970-01-01
            • 1970-01-01
            • 2017-04-27
            相关资源
            最近更新 更多