JSON Decode does not work as expected swift 4

核能气质少年 提交于 2020-03-17 03:21:53

问题


if I want to decode my JSON there is something weird happening.

Here's the structs

struct chatMessages : Codable {
    var message: [chatMessage]
}

struct chatMessage : Codable {
    var user: String
    var message: String
    var status: String
    var latitude: Double
    var longitude: Double

    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        user = try values.decode(String.self, forKey: .user)
        message = try values.decode(String.self, forKey: .message)
        status = try values.decode(String.self, forKey: .status)
        latitude = try values.decodeIfPresent(Double.self, forKey: .latitude) ?? 0.0
        longitude = try values.decodeIfPresent(Double.self, forKey: .longitude) ?? 0.0
    }
}

And here the function

   func loadChats() {
        print("Try to load chats...")
        do {
        let jsonData = W.getDataAsData(chatURL)
            print(jsonData)
            print(String.init(data: jsonData, encoding: .utf8)!)
            print("-----------")
            let jsonDecoder = JSONDecoder()
            let chatMessage1 = try jsonDecoder.decode(chatMessage.self, from: jsonData)
            print(chatMessage1)
        }
        catch {
            print("Something went wrong")
            print("\(error)")
        }
    }

if the returned JSON is {"user":"test","message":"Hello welcome","status":"admin","latitude":0,"longitude":0}.

its returning chatMessage(user: "test", message: "Hello welcome", status: "admin", latitude: 0.0, longitude: 0.0)

but if there are more messages e.g. [{"user":"user1","message":"Hello welcome","status":"admin","latitude":0,"longitude":0},{"user":"user2","message":"Hello welcome","status":"admin","latitude":0,"longitude":0}] I cannot get it to work. Its returning typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

I've tried with chatMessages.self but that didn't go as expected. What am I doing wrong?

Thanks in advance.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/51801349/json-decode-does-not-work-as-expected-swift-4

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