如何从响应数据结构构造 Codable

问题描述

如何从响应数据中对 Any & JSONNull 进行编码

Json 响应数据

"userType": {
        "id": "5f18J20a21n","name": "userName","name_prefix": null,"group": []
    }

用户类型模型类

struct UserType : Codable {
    let id : String?
    let name : String?
    let namePrefix: JSONNull? // I replace JSONNull with String,Is it good way to do so?
    let group : [JSONAny?]?

    enum CodingKeys: String,CodingKey {

        case id = "id"
        case name = "name"
        case namePrefix = "name_prefix"
        case group = "group"
    }

init(from decoder: Decoder) throws {
    let values = try decoder.container(keyedBy: CodingKeys.self)
        id = try values.decodeIfPresent(String.self,forKey: .id)
        name = try values.decodeIfPresent(String.self,forKey: .name)
        namePrefix = try values.decodeIfPresent(String.self,forKey: . namePrefix)
       // namePrefix = try values.decodeIfPresent(JSONNull.self,forKey: . namePrefix)
        group = try values.decodeIfPresent([JSONAny].self,forKey: .group)
        // Type of expression is ambiguous without more context
    }
}

我尝试了上面的代码,但出现错误

表达类型不明确,没有更多上下文

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)