Xcode json error



我现在正在学习Xcode,我有一个项目,它使用php从Mysql数据库中提取数据,并通过json将其传递给我的应用程序。在数据库中,所有 varchar 都设置为 utf8_bin。

这是 PHP:

header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo json_encode($this->Idea_model->get($id));

以下是输出的 JSON 的狙击:

[{"id":"1","title":"JWT blood sucka","objective":"test ","mission":"test","design_time":"80","development_time":"80","votes":"0","user_id":"0","date_created":"2012-08-03","date_modified":"2012-08-03","active":"1"},{"id":"2","title":"ford - liveDealer","objective":"to increce ","mission":"thid id a es","design_time":"80","development_time":"80","votes":"1","user_id":"1","date_created":"0000-00-00","date_modified":"0000-00-00","active":"1"}]

在 xcode 中,我正在使用此函数拉入 JSON [参考教程:http://www.raywenderlich.com/5492/working-with-json-in-ios-5]

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

当我使用教程中的这个 JSON 文件时,它可以工作http://api.kivaws.org/v1/loans/search.json?status=fundraising

但是当我使用我的 JSON 文件时,出现以下错误。

[8690:207] -[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x6a10400
Current language:  auto; currently objective-c

显然,我的 JSON 输出存在问题,因为我在 PHP 文件中打印了教程文件中的内容,并且这也有效。

我还尝试过在iOS模拟器中"重置内容和设置"。

有什么想法吗?

返回的对象似乎是一个数组,但您的代码将其视为字典(json 对象/哈希)

错误告诉你:它说消息objectForKey:(这是NSDictionary上的方法)正在发送到__NSCFArray的实例,这是一个NSArray的实现类,因此我的假设......

是的,我有一个想法 -

-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x6a10400

数组不是字典。 他们不响应对象ForKey他们响应对象索引;

当你有字典时,你认为你有一个数组。

常见的 JSON 错误。

下面是你的数据:

这是一个列表

从这里开始 --> "[" 然后对象从这里开始 "{"

[{"id":"1","title":"JWT blood sucka","objective":"test ","mission":"test","design_time":"80","development_time":"80","votes":"0","user_id":"0","date_created":"2012-08-03","date_modified":"2012-08-03","active":"1"}

然后是逗号 ","然后是列表中的下一项,以 { "{"id":"2","title":"ford - liveDea

开头

JSON说列表是一个数组,一个对象是一个字典,所以翻转你的代码

 (void)fetchedData:(NSData *)responseData {
  //parse out the json data
     NSError* error;
     NSArray* latestLoans = [NSJSONSerialization 
                  JSONObjectWithData:responseData //1
                  options:kNilOptions 
                  error:&error];
     NSLog(@"loans: %@", latestLoans); //3
     for (int i=0; i < latestLoans.count; i++) 
     {
        NSDictionary *myLoan = (NSDictionary*)[latestLoans objectAtIndex:i];
        NSLog(@"loan:%@", myLoan);
     }

....

明白了?

最新更新