JSON解码无法按预期的速度快速运行4

时间:2018-08-11 15:50:59

标签: json swift jsondecoder

如果我想解码JSON,则会发生一些奇怪的事情。

这是结构

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
    }
}

这里是函数

   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)")
        }
    }

如果返回的JSON是 {"user":"test","message":"Hello welcome","status":"admin","latitude":0,"longitude":0}

其返回chatMessage(user: "test", message: "Hello welcome", status: "admin", latitude: 0.0, longitude: 0.0)

,但是如果还有更多消息,例如[{"user":"user1","message":"Hello welcome","status":"admin","latitude":0,"longitude":0},{"user":"user2","message":"Hello welcome","status":"admin","latitude":0,"longitude":0}]我无法使用它。 返回typeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))

我尝试过使用chatMessages.self,但是并没有按预期进行。 我在做什么错了?

谢谢。

2 个答案:

答案 0 :(得分:2)

答案很简单, 您必须使用此:

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

代替此:

let chatMessage1 = try jsonDecoder.decode(chatMessage.self, from: jsonData)
在loadChats()函数中

。 因为您有NSDictionary数组。

答案 1 :(得分:2)

您可以在init(decoder)内部检测到并处理它,但是简单的解决方案是做到这一点

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

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

另外,我认为即使只有一条消息,也最好更改后端以不返回数组