【发布时间】:2017-08-14 09:10:23
【问题描述】:
我想将我的 json 响应转换为一个数组,但它不起作用,我收到一个错误,提示我数组中的项目为零
func getcomments(){
RestApiManager.sharedInstance.getComments(TUTORIAL_ID: id){
response in
let comments = JSON(response)
for item in comments.array!{
let comment = Comment(memail: String(describing: item["email"]), mcomment: String(describing: item["comment"]), mcomment_date: String(describing: item["comment_date"]), manswer: String(describing: item["answer"]), manswer_date: String(describing: item["answer_date"]))
self.comments.append(comment)
}
}
}
这是我的 json 响应:
[{
"email": "-",
"comment": "\u0627\u0632 \u0627\u067e\u0644\u06cc\u06a9\u06cc\u0634\u0646 \u062e\u0648\u0628\u062a\u0648\u0646 \u0645\u0645\u0646\u0648\u0646\u0645",
"comment_date": "2017-07-15 19:30:00",
"answer": null,
"answer_date": null
},
{
"email": "S.M_Emamian@yahoo.com",
"comment": "salam",
"comment_date": "2017-07-11 19:30:00",
"answer": "\u062a\u0634\u06a9\u0631",
"answer_date": "2017-07-12 03:50:57"
}
]
我在这一行得到 nil 错误:
在展开可选值时意外发现 nil
for item in comments.array!
【问题讨论】:
-
就在这里
comments.array!如果你要敲什么东西,最好确保它不是零。我不认为你可以在这里保证。显然不是,因为它崩溃了。 -
response的类型是什么?如果是字符串则需要使用JSON(parseJSON:) -
@sweeper 是的,我需要 JSON(parseJSON:) 它可以工作,谢谢
-
@fazed 我作为答案发布。请考虑通过单击该复选标记接受它!