2017-08-14 106 views
0

我想我的JSON響應轉換成數組,但它不工作,我得到了我說的陣列中的項目是零轉換JSON數據陣列中swift3

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": "[email protected]", 
     "comment": "salam", 
     "comment_date": "2017-07-11 19:30:00", 
     "answer": "\u062a\u0634\u06a9\u0631", 
     "answer_date": "2017-07-12 03:50:57" 
    } 
] 

我在這一行了零誤差:

意外發現零而展開的可選值

for item in comments.array! 
+0

就在這裏'comments.array!'如果你要爆炸的東西,你最好確定它不是零。我認爲你不能在這裏保證。顯然不是,因爲它墜毀了。 – Abizern

+2

「響應」的類型是什麼?如果它是一個字符串,你需要使用'JSON(parseJSON :)' – Sweeper

+0

@sweeper是我需要JSON(parseJSON :)它的工作原理謝謝 – fazed

回答

0

根據您的意見,response實際上是一個字符串。因此,您不能僅使用init(_:)創建JSON。你需要init(parseJSON:)

init(_:)只會使用該字符串而不是JSON對象創建JSON,這顯然不是您想要的。 init(parseJSON:)將實際解析您的JSON字符串,並允許您訪問不同的鍵值對。

func getcomments(){ 
    RestApiManager.sharedInstance.getComments(TUTORIAL_ID: id){ 
     response in 
     let comments = JSON(parseJSON: response) 
1

如果將它解碼爲結構數組,它會更容易。

首先,創建結構:

struct Comment: Codable { 
    var email: String 
    var comment: String 
    var comment_date: String 
    var answer: String 
    var answer_date: String 
} 

然後,你可以調用JSON這樣的:

guard let url = Bundle.main.url(forResource: resource, withExtension: "json") else { 
    throw Errors.couldNotFindResource 
} 
data = try! JSONDecoder().decode([Comment].self, from: Data(contentsOf: url))