繁体   English   中英

在Swift中使用Codable解析JSON响应

[英]Parsing JSON response using Codable in Swift

我将收到带有对象数组的API响应作为JSON。 例如,

{
        "Header": "Verification",
        "Info": [
            {
                "mobile": "**** **** 123"
            },
            {
                "email": "s******k**@g***.com"
            }
        ],
}

我使用了Codable功能并创建了如下的Struct,

struct cResponse: Codable 
{
  var Header: String?
  var Info: [Info] 
}

struct Info: Codable {
  var mobile: String!
  var email: String!
}

我试图通过使用JSONDecoder迅速解码JSON响应,如以下代码所示,

let decoder = JSONDecoder()
let decodedcRES: cResponse = try decoder.decode(cResponse.self, from: CData)

直到服务器上的信息仅是手机和电子邮件为止,此方法才能正常工作。

但是,Info在运行时将是动态的(即),我将从服务器收到Info下的更多JSON对象。 因此,如果我创建如下所示的Struct,

struct cResponse: Codable 
{
  var Header: String?
  var Info: [String] 
}

我收到“由于格式不正确,无法读取数据”。 作为错误。

如何使用Codable功能快速处理动态JSON数组对象?

Info是对象数组,因此您可以进行类似的操作以对其进行解析。

struct cResponse: Codable 
{
  var Header: String?
  var Info: [[String : String]] 
}

信息键包含对象数组,因此将结构更改为:

struct cResponse: Codable
{
    var Header: String?
    var Info: [[String: String]]
}

更好的方法是使用Custom枚举作为Decodable:

enum ContactType: Decodable {
    case email(String)
    case mobile(String)
    case unknown
    enum MyKeys: String, CodingKey {
        case email
        case mobile
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: MyKeys.self)
        if let emailString = try? container.decode(String.self, forKey: .email) {
            self = .email(emailString)
        } else if let mobileString = try? container.decode(String.self, forKey: .mobile) {
            self = .mobile(mobileString)
        } else {
            self = .unknown
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM