iOS JSON Parse无法正常工作(返回null字典)

时间:2012-08-22 10:32:36

标签: ios json parsing nsjsonserialization

我使用NSJSONSerialization的{​​{1}}来解析从服务器返回的JSON数据。

现在我使用的选项参数:JSONObjectWithData:data options: error:。您可以在下面查看实际的JSON(我相信问题所在)。

我收到的错误消息是:

  

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

知道怎么解决吗?

JSON =

NSJSONReadingAllowFragments

6 个答案:

答案 0 :(得分:12)

可能你有一些你看不到的不可打印的角色。试试这个:

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字典上运行上述内容 - 无法解析的字典。

答案 1 :(得分:2)

我已经意识到这个问题是这样一个事实,即从URL返回的是一个HTML页面,所有这些html,head和body标签都围绕着实际的响应,所以它无法被解析。关于如何从响应中删除HTML标记(在将其更改为字符串之后),这是一个很好的Q&amp; A:Remove HTML Tags from an NSString on the iPhone

答案 2 :(得分:1)

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

<html>
<body>
<?php

?>
</body>
</html>

会破坏你的结果。把它变成:

<?php

?> 

为我工作。

答案 3 :(得分:0)

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

  

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

答案 4 :(得分:0)

有一种方法,您可以通过邮寄请求解析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委托: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 ])
{

}


}

答案 5 :(得分:0)

您还可以在ios中按块查找json数据的网址

 #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
}