codable

json swift4 how to set the struct?

[亡魂溺海] 提交于 2019-12-11 06:17:16
问题 I want to parse a json from a http resource (it's my router so http is mandatory). After I set the Info.plist App Security Transport that I do get a connection I get the data by 1st Attempted: let sphDataAddress = "http://speedport.ip/data/status.json" let url = URL(string: sphDataAddress)! let jsonData = try! Data(contentsOf: url) // ! is just for testing reason and will be in real app by guard let print("data \(jsonData)") // shows that the received Data are 5077bytes struct User { let

Codable NSManagedObject fail on decodeIfPresent Data type

岁酱吖の 提交于 2019-12-11 06:01:17
问题 I obtain this error when i'm trying to decode this json: [{ "id": "76f22c25-cee7-4c7a-94fa-1fb85720f580", "purchaseDate": "2012-04-05T19:03:43Z", "title": "azare", }, { "id": "9b4b9f7d-382f-4555-9eaa-97939b13633f", "purchaseDate": "2012-04-05T19:02:46Z", "title": "Chocolat", }, { "id": "02a0aa06-2d0c-4ab9-aaaa-af7dee7b4845", "purchaseDate": "2012-09-24T17:39:52Z", "title": "Some thing", }] Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift

Parse Codable classes and avoid repetition

烂漫一生 提交于 2019-12-11 01:51:31
问题 I have a JSON response as the following: { "http_status": 200, "success": true, "has_error": false, "error": [ "" ], "response": { "token": "", "verified": false, "message": "" } } As far as i can say for an app API usage http_status, success, has_error, error are shared between all APIS and thus i will create a Codable class to handle it, but the response could be different model, so here is what I'm trying to do. I have created a general response class as the below, so this class i can use

Explit conformance to Codable removes memberwise initializer generation on structs

▼魔方 西西 提交于 2019-12-10 13:19:55
问题 Given: struct Foo { let bar: Bar } I get a convenience initializer to use: let foo = Foo(bar: Bar()) But if Bar isn't itself Codable , or for some other reason I need to explicitly implement Codable on Foo then the convenience memberwise initializer is no longer present: struct Foo: Codable { init(from decoder: Decoder) throws { } func encode(to encoder: Encoder) throws { } let bar: Bar } and i get: let foo = Foo(bar: Bar()) Incorrect argument label in call (have 'bar:', expected 'from:') Is

Whats wrong with Codable function?

风格不统一 提交于 2019-12-10 12:26:25
问题 Following is my JSON: { "Books":[ { "title":"book title", "Contents":[ { "figure":"Clause33", "url":"PressureReleifValve.html", "type":"video" } ] } ] } Here is the structure: The content might have multiple items in it. struct Books: Codable { let title: String let contents: [Content] } struct Content: Codable { let figure, url, type: String } Here is the code: guard let books = try? JSONDecoder().decode(Books.self, from: jsonData2) else { fatalError("The JSON information has errors") }

Swift 4 Codable decoding json

烂漫一生 提交于 2019-12-09 06:04:16
问题 I'm trying to implement the new Codable protocol, so I added Codable to my struct, but am stuck on decoding the JSON . Here's what I had before: Struct - struct Question { var title: String var answer: Int var question: Int } Client - ... guard let data = data else { return } do { self.jsonResponse = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] let questionItems = self.jsonResponse?["themes"] as! [[String: Any]] questionItems.forEach { let item =

Encode nil value as null with JSONEncoder

三世轮回 提交于 2019-12-08 23:34:40
问题 I'm using Swift 4's JSONEncoder . I have a Codable struct with an optional property, and I'd like this property to show up as null value in the produced JSON data when the value is nil . However, JSONEncoder discards the property and does not add it to the JSON output. Is there a way to configure JSONEncoder so that it preserves the key and sets it to null in this case? Example The code snippet below produces {"number":1} , but I'd rather like it to give me {"string":null,"number":1} : struct

Decode json output to a model

孤街浪徒 提交于 2019-12-08 11:29:49
问题 I have this json output that I want to parse using Codable: { "success": true, "total": 1, "users": [ { "user": { "id": "1", "fname": "admin", "lname": "admin", "login": "admin", "actif": "0", "last_connection_date": "2018-01-18 16:02:34" } } ], "msg": "" } And I just want to exctact the user's informations out of it. My user's model import RealmSwift class User: Object, Codable { @objc dynamic var id: String = "" @objc dynamic var fname: String = "" @objc dynamic var lname: String = "" @objc

Swift: How to decode result from api which is being returned as a string or as a string of array?

末鹿安然 提交于 2019-12-08 10:58:19
问题 I am using NSUrlConnection and Codable library of Apple. I am using a web API to signup new users for my application. The API returns a status and a message (in json which i map to a model). This is my model class: Struct SignUpResult { let message: String let status: String } Struct SignUpParams { let name: String let email: String let mobile_no: String let password: String } If the user gave all the parameters correctly then the message is returned as a string. Like this: { "status": "OK",

Decode all properties in custom init (enumerate over all properties of a class and assign them a value)

混江龙づ霸主 提交于 2019-12-08 10:19:46
问题 I'm currently working on a project that it's API isn't ready yet. So sometimes type of some properties changes. For example I have this struct: struct Animal: Codable { var tag: Int? var name: String? var type: String? var birthday: Date? } for this json: { "tag": 12, "name": "Dog", "type": "TYPE1" } But in development, the json changes to something like this: { "tag": "ANIMAL", "name": "Dog", "type": 1 } So I get some type mismatch error in decoder and nil object . To prevent decoder from