获取代码“无法识别的选择发送到实例”为iOS8上

问题描述:

在ios7此代码的工作,但现在我得到的错误: - [__ NSCFString objectForKeyedSubscript:]:无法识别的选择发送到实例获取代码“无法识别的选择发送到实例”为iOS8上

.m文件

//get the JSON response 
NSDictionary *jsonData = [NSJSONSerialization 
          JSONObjectWithData:urlData 
          options:NSJSONReadingMutableContainers 
          error:&error]; 
//Parses the "success" value 
success = [jsonData[@"success"] integerValue]; 

//Was it successful? 
if(success){ 
    //successful, save the profile gathered into global gMyProfile 
    NSArray *profileJSON=jsonData[@"myProfile"]; 
    for (NSDictionary* dict in profileJSON) 
    { 
     NSLog(@"First_Name: %@", dict [@"first_name"]); 
    ... 

错误发生在NSLog声明上,并且来自一点研究,它抱怨字典[@“first_name”]);

login.py

.... 
#Query for user 
db_cursor = db.cursor(MySQLdb.cursors.DictCursor) 
db_query = """SELECT users.email, users.first_name, users.profile_pic_path, \ 
       FROM users,data WHERE users.email='%s' \ 
       AND users.user_id=data.user_id""" % user_email 
db_cursor.execute(db_query) 

#If there is one record containing the username check password 
if(db_cursor.rowcount == 1): 
    user_profile = db_cursor.fetchone() 
... 
    json_obj= {'success': 1, 'myProfile': user_profile,} 
... 

JSON输出:

{'myProfile': {'first_name': 'Matt', 'email': '[email protected]', 'profile_pic_path': 'default'}, 'success': 1} 

所有这些代码是工作,我没有改变任何东西。 任何帮助将不胜感激!!!!

+0

没有看到JSON,我们不能做太多。 – 2014-09-26 17:18:16

+0

用JSON输出编辑帖子:) – lr100 2014-09-26 17:26:44

+0

转到json.org并研究JSON语法。学习只需要5-10分钟。然后回到这里并解释你的代码是如何构成的。 – 2014-09-26 17:37:57

dict不是一本字典。它是一个字符串。打印它,你会知道它是哪个字符串。

更可能的是,您的JSON不是您认为的那样。特别是,myProfile值是字符串而不是字典。

如果fetchone()返回None,会发生什么情况;你最终在你的JSON中的字符串?

+0

我只是困惑,为什么这在ios7中运行良好。它完美地解析和保存数据。不适宜研究它:) – lr100 2014-09-26 17:56:38

+1

@ lr100 - 当有多个数据集时,另一端可能发送一个数组,而只有一个数据集时发送一个对象。这并不常见,但并非前所未闻。如果是这种情况,则需要测试收到的内容以确定“myProfile”是数组还是字典。 – 2014-09-26 19:19:55

+0

@HotLicks说什么;你应该拆开接收到的JSON并验证数据的结构。即使在生产中,您也可能想要针对JSON数据中的意外类型加强代码。 – bbum 2014-09-26 20:22:54

改变了的.m

//Was it successful? 
if(success){ 
    //successful, save the profile gathered into global gMyProfile 
    NSArray *profileJSON=jsonData[@"myProfile"]; 
    for (NSDictionary* dict in profileJSON) 
    { 
    ... 

//Was it successful? 
if(success){ 
    //successful, save the profile gathered into global gMyProfile 
    NSDictionary* dict=jsonData[@"myProfile"]; 
    //no more for loop 
    ... 

蛇皮JSON模块返回单个字典而不是单个字典的阵列时,有一种元素。如果有多个,它将​​返回一个字典数组。

不知道为什么这并没有给我在ios7的麻烦,但在ios8。