JSON解码无法按预期方式快速运行4 [英] JSON Decode does not work as expected swift 4

查看:93
本文介绍了JSON解码无法按预期方式快速运行4的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这是结构

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

if the returned JSON is {"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))

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

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

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

谢谢.

推荐答案

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

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

这篇关于JSON解码无法按预期方式快速运行4的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆