JSON Decode does not work as expected swift 4

倖福魔咒の 提交于 2019-12-02 13:10:41

You can detect this inside init(decoder) and handle it , but the simple solution is to do this

 do {
       let chatMessage1 = try jsonDecoder.decode(chatMessage.self, from: jsonData)
   }
 catch {

    do {
        let chatMessage1 = try jsonDecoder.decode([chatMessage].self, from: jsonData)
     }
     catch {
        print(error)
      }
}

also i think it's best to change your backend to return array anway if even there is only one message

The answer is very simple , you must use this :

let chatMessage1 = try jsonDecoder.decode([chatMessage].self, from: jsonData)

instead of this :

let chatMessage1 = try jsonDecoder.decode(chatMessage.self, from: jsonData)

in loadChats() function. because you have array of NSDictionary.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!