codable

Swift Codable init

不羁的心 提交于 2019-12-06 02:52:16
问题 I would like to do some initialization logic after the Swift Coding/Encoding feature has finished decoding a JSON. struct MyStruct: Codable { let id: Int var name: String init() { name = "\(id) \(name)" } } But I get the compiler error: Return from initializer without initializing all stored properties Which is clear to me because init() wants me to initialise all properties. But adding an init() with all needed properties also doesn't solve it because this initializer is not called(!) when

Extracting data from JSON array with swift Codable

懵懂的女人 提交于 2019-12-06 01:38:45
I have a JSON response like this: I have currently designed my decodable struct to be as follows: struct PortfolioResponseModel: Decodable { var dataset: Dataset struct Dataset: Decodable { var data: Array<PortfolioData> //I cannot use [Any] here... struct PortfolioData: Decodable { //how to extract this data ? } } } The question is, how do I extract the data inside the array, which can have a value Double or String. Here is the sample string to make this work on playground: let myJSONArray = """ { "dataset": { "data": [ [ "2018-01-19", 181.29 ], [ "2018-01-18", 179.8 ], [ "2018-01-17", 177.6

Decoding an Array with Swift4 Codable

此生再无相见时 提交于 2019-12-05 17:22:47
I'm playing around with Swift 4 Codable again and just when I think I have the hang of it, I get this issue with decoding the Weather key from the response. let jsonData = """ {"coord":{"lon":-113,"lat":35}, "weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}], "base":"stations", "main":{"temp":291.15,"pressure":1022,"humidity":72,"temp_min":291.15,"temp_max":291.15}, "visibility":16093,"wind":{"speed":3.6,"deg":200}, "clouds":{"all":1}, "dt":1503294780,"sys":{"type":1,"id":321,"message":0.184,"country":"US","sunrise":1503320222,"sunset":1503367937}, "id":5308281,"name"

The `convertFromSnakeCase` strategy doesn't work with custom `CodingKeys` in Swift

て烟熏妆下的殇ゞ 提交于 2019-12-05 16:40:44
问题 I try to use Swift 4.1's new feature to convert snake-case to camelCase during JSON decoding. Here is the example: struct StudentInfo: Decodable { internal let studentID: String internal let name: String internal let testScore: String private enum CodingKeys: String, CodingKey { case studentID = "student_id" case name case testScore } } let jsonString = """ {"student_id":"123","name":"Apple Bay Street","test_score":"94608"} """ do { let decoder = JSONDecoder() decoder.keyDecodingStrategy =

Swift codable, Default Value to Class property when key missing in the JSON

心已入冬 提交于 2019-12-05 15:56:57
As you know Codable is new stuff in swift 4, So we gonna move to this one from the older initialisation process for the Models. Usually we use the following Scenario class LoginModal { let cashierType: NSNumber let status: NSNumber init(_ json: JSON) { let keys = Constants.LoginModal() cashierType = json[keys.cashierType].number ?? 0 status = json[keys.status].number ?? 0 } } In the JSON cashierType Key may missing, so we giving the default Value as 0 Now while doing this with Codable is quite easy, as following class LoginModal: Coadable { let cashierType: NSNumber let status: NSNumber } as

How to represent a generic JSON structure in Swift?

我的梦境 提交于 2019-12-05 08:39:52
I would like to represent a generic JSON object in Swift: let foo: [String: Any] = [ "foo": 1, "bar": "baz", ] But the [String: Any] type suggested by the compiler doesn’t really work well. I can’t check two instances of the type for equality, for example, while that should be possible with two JSON trees. What also doesn’t work is using the Codable machinery to encode that value into a JSON string: let encoded = try JSONEncoder().encode(foo) Which blows up with an error: fatal error: Dictionary<String, Any> does not conform to Encodable because Any does not conform to Encodable. I know I can

Swift 4 Codable - API provides sometimes an Int sometimes a String

痞子三分冷 提交于 2019-12-05 07:40:53
问题 I have Codables running now. But the API has some String entries that can sometimes have an Int value of 0 if they are empty. I was searching here and found this: Swift 4 Codable - Bool or String values But I'm not able to get it running My struct struct check : Codable { let test : Int let rating : String? } Rating is most of the time something like "1Star" . But if there is no rating I get 0 as Int back. I'm parsing the data like this: enum Result<Value> { case success(Value) case failure

Swift 4 Decodable: struct from nested array

穿精又带淫゛_ 提交于 2019-12-04 23:07:17
问题 Given the following JSON document I'd like to create a struct with four properties: filmCount (Int), year (Int), category (String), and actor (Actor array). { "filmCount": 5, "year": 2018, "category": "Other", "actors":{ "nodes":[ { "actor":{ "id":0, "name":"Daniel Craig" } }, { "actor":{ "id":1, "name":"Naomie Harris" } }, { "actor":{ "id":2, "name":"Rowan Atkinson" } } ] } } PlacerholderData is a struct storing the three main properties and the list of actors which should be retrieved from

How do you design a codable JSON field which can be either an empty string or an int [closed]

≯℡__Kan透↙ 提交于 2019-12-04 15:39:53
How do you handle a field of a codable struct from JSON which can be either an empty string or an int? I tried using the data type any but that does not conform to codable. I think that if it does not have a value then it returns an empty string or otherwise, it returns an int. I am using Swift 4 and XCode 9. Thanks in advance I really would suggest changing that web service to return values consistently (and if there is no value for the integer type, don't return anything for that key). But if you're stuck with this design, you will have to write your own init(from:) which gracefully handles

Swift Codable protocol with recursive enums

隐身守侯 提交于 2019-12-04 13:22:56
问题 Let's say that I have a model like the following, which allows me to build a tree of Foo objects. struct Foo { var kind : Kind enum Kind { case node([Foo]) case leaf } } How can I make this Codable, specifically for the case node([Foo]) ? 回答1: Here's the final struct, based on the answer from @PauloMattos: Base Foo struct: struct Foo { var name: String var kind: Kind enum Kind { case node([Foo]) case leaf } init(name: String, kind: Kind) { self.name = name self.kind = kind } } Codable