我正在尝试打印(“_ id”)从服务器获取的数据

时间:2017-07-26 16:36:19

标签: ios arrays mongodb api nsdictionary

对于以下快速代码

 self.cardDataArray = response.value(forKey: "card_list") as? NSArray
 print(self.cardDataArray!)

我从服务器(API)获得此输出

(
        {
        "__v" = 0;
        "_id" = 5978b5dadc336d0788a81c58;
        "stu_number" = 1234567812345678;
        "stu_status" = 1;
        "created_at" = "2017-07-26T15:31:38.874Z";
        "stu_id" = 5978b41ddc336d0788a81c57;
        "stu_number" = 1234;
        "default_status" = 0;
        "default_type" = 3;
    }
)

我正在尝试从上面的代码中打印“_id” 但我得到错误 无法将'__NSSingleObjectArrayI'(0x1a9ae6ca0)类型的值转换为'NSString'

这是我试图打印的代码

let studentID = self.cardDataArray?.value(forKey: "_id") as! NSString
print(studentID)

1 个答案:

答案 0 :(得分:1)

您的cardDataArray是一个词典数组,因此您必须首先使用此词典并访问此案例中所需的密钥" _id",尝试使用此代码

if let studentDict = self.cardDataArray?[0] as? NSDictionary
{
   print(studentDict.object(forKey: "_id") as? NSString)
}

<强>更新

for dictObj in self.cardDataArray {
    print(dictObj.object(forKey: "_id") as? NSString)
}

希望这有帮助