繁体   English   中英

iOS JSON解析不起作用(返回空字典)

[英]iOS JSON Parse not working (returns null dictionary)

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

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

我收到的错误消息是:

错误域= NSCocoaErrorDomain代码= 3840“操作无法完成。(可可错误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"]}}

可能您有一些看不见的无法打印的角色。 尝试这个:

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字典上运行以上内容即可-解析失败的字典。

Ive明智地发现了问题所在,因为URL的返回是一个HTML页面,在实际响应周围附加了所有这些html,head和body标签,因此无法对其进行解析。 这是有关如何从响应中删除HTML标记(将其更改为字符串后)的很好的问答: 从iPhone上的NSString删除HTML标记

我有一段时间遇到同样的问题,我只是发现,如果我要从网页中提取数据(例如PHP页面),则该页面中不应有任何HTML标记。 像这样的结构:

<html>
<body>
<?php

?>
</body>
</html>

将破坏您的结果。 变成:

<?php

?> 

为我工作。

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

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

一种方法是,您可以通过发布请求解析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 ])
{

}


}

您还可以在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

我们需要做的第一件事是从Web下载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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM