Decode Json in Swift

发布
更新
字数 233
阅读 2 分钟
阅读量 588

JSONDecoder 支持策略设置用以兼容 web API 的 JSON 格式:

let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase
decoder.dateDecodingStrategy = .secondsSince1970
let launch = try decoder.decode(Person.self, from: jsonData)

可以使用 CodingKeys 自定义键名

struct Person {
    let name: String
}

extension Person: Decodable {
    enum CodingKeys: String, CodingKey {
        case name = "full_name"
    }
}

当 JSON 包含嵌套数据时,如:

{
  "name": "A Lan",
  "location": {
    "country": "China"
  }
  "age": 19
}
struct Person {
    let name: String
    let country: String
    let age: Int
}

extension Person: Decodable {
    enum CodingKeys: String, CodingKey {
        case name = "full_name"
        // 1. 别名
        case country = "location"
        case age
    }
    
    // 2. 定义一个新的枚举类型,匹配 Json 中的 location,拿到 country 值
    enum LocationKeys: String, CodingKey {
        case country
    }
    
    // 3. 自定义
    init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)

        name = try values.decode(String.self, forKey: .name)

        let location = try values.nestedContainer(keyedBy: LocationKeys.self, forKey: .country)
        country = try location.decode(String.self, forKey: .country)

        age = try values.decode(String.self, forKey: .age)
    }
}
    

当然,也可以选择创建一个 Location 对象,并指定一个 country 属性。