简体   繁体   English

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

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

I use the NSJSONSerialization 's JSONObjectWithData:data options: error: to parse JSON data returned from a server. 我使用NSJSONSerializationJSONObjectWithData:data options: error:解析从服务器返回的JSON数据。

Now for the options parameter I use: NSJSONReadingAllowFragments . 现在,对于options参数,我使用: NSJSONReadingAllowFragments You can look below and see the actual JSON (where I believe the problem is). 您可以在下面查看并查看实际的JSON(我认为问题出在哪里)。

The error message I get is: 我收到的错误消息是:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn't be completed. (Cocoa error 3840.)" (Invalid value around character 0.) UserInfo=0x6895da0 {NSDebugDescription=Invalid value around character 0.} 错误域= NSCocoaErrorDomain代码= 3840“操作无法完成。(可可错误3840。)”(字符0周围的无效值。)UserInfo = 0x6895da0 {NSDebugDescription =字符0周围的无效值。}

Any idea how to fix it? 知道如何解决吗?

JSON = 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"]}}

Probably you have some unprintable character that you cannot see. 可能您有一些看不见的无法打印的角色。 Try this: 尝试这个:

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);
}

To verify you don't have unprintable characters at the beginning or end of the data. 为了验证您在数据的开头或结尾处没有不可打印的字符。

EDIT: to clarify, just run the above on your JSON dictionary - the one that fails to parse. 编辑:澄清一下,只需在JSON字典上运行以上内容即可-解析失败的字典。

Ive acctualy discovered the problem to be the fact that the return from the URL is an HTML page, ant there all these html, head, and body tags around the actual response, so it can't be parsed. Ive明智地发现了问题所在,因为URL的返回是一个HTML页面,在实际响应周围附加了所有这些html,head和body标签,因此无法对其进行解析。 This is a good Q&A on how to remove the HTML tags from the response (after it has been changed into a string) : Remove HTML Tags from an NSString on the iPhone 这是有关如何从响应中删除HTML标记(将其更改为字符串后)的很好的问答: 从iPhone上的NSString删除HTML标记

I had the same problem for a while, I just figured out that if I'm pulling data from a webpage let's say PHP page, there should not be any HTML tags in that page. 我有一段时间遇到同样的问题,我只是发现,如果我要从网页中提取数据(例如PHP页面),则该页面中不应有任何HTML标记。 So a structure like: 像这样的结构:

<html>
<body>
<?php

?>
</body>
</html>

will ruin your result. 将破坏您的结果。 turning it into: 变成:

<?php

?> 

worked for me. 为我工作。

It's been a while but an easier way of printing the data is: 已经有一段时间了,但是打印数据的一种更简单的方法是:

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

One way is there , you can parse jsondata by post request 一种方法是,您可以通过发布请求解析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]; 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 { }-(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 ])
{

}


}

You can also hit url for json data by block in ios 您还可以在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

The first thing we need to do is download the JSON data from the web. 我们需要做的第一件事是从Web下载JSON数据。 Luckily, with GCD we can do this in one line of code! 幸运的是,有了GCD,我们可以在一行代码中做到这一点! Add the following to ViewController.m: 将以下内容添加到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