codable

Hot to decode JSON data that could and array or a single element in Swift?

早过忘川 提交于 2021-01-15 19:13:51
问题 I have a struct named Info which is decoded based on the data it receives. But sometimes, one of the values in data can either be a double or an array of double. How do I set up my struct for that? struct Info: Decodable { let author: String let title: String let tags: [Tags] let price: [Double] enum Tags: String, Decodable { case nonfiction case biography case fiction } } Based on the url, I either get price as a double { "author" : "Mark A", "title" : "The Great Deman", "tags" : [

Hot to decode JSON data that could and array or a single element in Swift?

丶灬走出姿态 提交于 2021-01-15 19:08:17
问题 I have a struct named Info which is decoded based on the data it receives. But sometimes, one of the values in data can either be a double or an array of double. How do I set up my struct for that? struct Info: Decodable { let author: String let title: String let tags: [Tags] let price: [Double] enum Tags: String, Decodable { case nonfiction case biography case fiction } } Based on the url, I either get price as a double { "author" : "Mark A", "title" : "The Great Deman", "tags" : [

Using Codable to encode/decode from Strings to Ints with a function in between

此生再无相见时 提交于 2020-12-30 04:22:17
问题 I have this json string: let json = """ { "name": "Wendy Carlos", "hexA": "7AE147AF", "hexB": "851EB851" } """ let data = Data(json.utf8) ...which I'd like to encode to (and back from) this struct, using Codable: struct CodeMe: Codable { var name: String var hexA: Int var hexB: Int enum CodingKeys: String, CodingKey { case name, hexA, hexB } } let encoder = JSONEncoder() let decoder = JSONDecoder() But hexA and hexB are Strings (in the JSON) and I need these to be Ints in the Swift object. I