【问题标题】:JSON Decode does not work as expected swift 4JSON解码不能按预期工作 swift 4
【发布时间】:2018-08-11 15:50:59
【问题描述】:

如果我想解码我的 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,但这并没有按预期进行。 我做错了什么?

提前致谢。

【问题讨论】:

    标签: json swift jsondecoder


    【解决方案1】:

    您可以在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)
          }
    }
    

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

    【讨论】:

      【解决方案2】:

      答案很简单, 你必须使用这个:

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

      而不是这个:

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

      在 loadChats() 函数中。 因为你有 NSDictionary 数组。

      【讨论】:

      • 不是用 this 代替 this ,内容可能是字典或数组,所以这两种情况仍然存在
      • 响应必须是固定结构。所以你根据它解码。
      猜你喜欢
      • 1970-01-01
      • 2015-06-26
      • 2013-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多