let decoder =JSONDecoder() do { let wrapper =try decoder.decode(EntityWrapper.self, from: jsonData) let entity = wrapper.entity print(entity) } catch {}
let decoder =JSONDecoder() // 自定义日期解码策略 decoder.dateDecodingStrategy = .custom({ dec in let container =try dec.singleValueContainer() let text =try container.decode(String.self)
let df =DateFormatter()
df.dateFormat ="yyyy-MM-dd" iflet date = df.date(from: text) { return date }
df.dateFormat ="yyyy/MM/dd" iflet date = df.date(from: text) { return date }
returnDate() }) do { let entity =try decoder.decode(Entity.self, from: jsonData) print(entity) } catch {}
Key、property使用不同的命名规则
指的是JSON与模型,一个使用下划线命名法,另一个使用驼峰命名法
JSON:
1 2 3 4
{ "full_name":"Bill Gates", "country":"USA" }
模型:
1 2 3 4
structEntity: Codable { var fullName: String var country: String }
解析:
1 2 3 4 5 6 7 8 9
let jsonData = jsonText.data(using: .utf8)!
let decoder =JSONDecoder() // 下划线命名法 ----> 驼峰命名法 decoder.keyDecodingStrategy = .convertFromSnakeCase do { let entity =try decoder.decode(Entity.self, from: jsonData) print(entity) } catch {}