codable

Use swift Codable to decode JSON with values as keys

纵然是瞬间 提交于 2019-11-26 14:46:08
问题 I have a problem decoding a JSON structure which I cannot change to make it easier to decode (it's coming from firebase).. How do I decode the following JSON into objects? The problem is how to convert "7E7-M001". It's the name of a container which has drawers. The drawers name is also used as a key. { "7E7-M001" : { "Drawer1" : { "101" : { "Partnumber" : "F101" }, "102" : { "Partnumber" : "F121" } } }, "7E7-M002": { "Drawer1": { "201": { "Partnumber": "F201" }, "202": { "Partnumber": "F221"

Using JSONEncoder to encode a variable with Codable as type

◇◆丶佛笑我妖孽 提交于 2019-11-26 14:18:59
问题 I managed to get both JSON and plist encoding and decoding working, but only by directly calling the encode/decode function on a specific object. For example: struct Test: Codable { var someString: String? } let testItem = Test() testItem.someString = "abc" let result = try JSONEncoder().encode(testItem) This works well and without issues. However, I am trying to get a function that takes in only the Codable protocol conformance as type and saves that object. func saveObject(_ object:

How to use Any in Codable Type

拜拜、爱过 提交于 2019-11-26 13:56:31
问题 I'm currently working with Codable types in my project and facing an issue. struct Person: Codable { var id: Any } id in the above code could be either a String or an Int . This is the reason id is of type Any . I know that Any is not Codable . What I need to know is how can I make it work. 回答1: Codable needs to know the type to cast to. Firstly I would try to address the issue of not knowing the type, see if you can fix that and make it simpler. Otherwise the only way I can think of solving

Swift 4 JSON Decodable simplest way to decode type change

邮差的信 提交于 2019-11-26 13:07:45
问题 With Swift 4\'s Codable protocol there\'s a great level of under the hood date and data conversion strategies. Given the JSON: { \"name\": \"Bob\", \"age\": 25, \"tax_rate\": \"4.25\" } I want to coerce it into the following structure struct ExampleJson: Decodable { var name: String var age: Int var taxRate: Float enum CodingKeys: String, CodingKey { case name, age case taxRate = \"tax_rate\" } } The Date Decoding Strategy can convert a String based date into a Date. Is there something that

Using Decodable in Swift 4 with Inheritance

天大地大妈咪最大 提交于 2019-11-26 13:02:01
Should the use of class inheritance break the Decodability of class. For example, the following code class Server : Codable { var id : Int? } class Development : Server { var name : String? var userId : Int? } var json = "{\"id\" : 1,\"name\" : \"Large Building Development\"}" let jsonDecoder = JSONDecoder() let item = try jsonDecoder.decode(Development.self, from:json.data(using: .utf8)!) as Development print(item.id ?? "id is nil") print(item.name ?? "name is nil") here output is: 1 name is nil Now if I reverse this, name decodes but id does not. class Server { var id : Int? } class

How to use swift 4 Codable in Core Data?

北城余情 提交于 2019-11-26 11:13:49
Codable seems a very exciting feature. But I wonder how we can use it in Core Data? In particular, is it possible to directly encode/decode a JSON from/to a NSManagedObject? I tried a very simple example: and defined Foo myself: import CoreData @objc(Foo) public class Foo: NSManagedObject, Codable {} But when using it like this: let json = """ { "name": "foo", "bars": [{ "name": "bar1", }], [{ "name": "bar2" }] } """.data(using: .utf8)! let decoder = JSONDecoder() let foo = try! decoder.decode(Foo.self, from: json) print(foo) The compiler failed with this errror: super.init isn't called on all

Encode/Decode Array of Types conforming to protocol with JSONEncoder

*爱你&永不变心* 提交于 2019-11-26 09:19:39
问题 I\'m trying to find the best way to Encode/Decode an array of structs conforming to a swift protocol using the new JSONDecoder/Encoder in Swift 4. I made up a little example to illustrate the problem: First we have a protocol Tag and some Types that conform to this protocol. protocol Tag: Codable { var type: String { get } var value: String { get } } struct AuthorTag: Tag { let type = \"author\" let value: String } struct GenreTag: Tag { let type = \"genre\" let value: String } Then we have a

Using codable with key that is sometimes an Int and other times a String

荒凉一梦 提交于 2019-11-26 05:31:41
问题 I have an API that will sometimes return a specific key (in this case id ) in the JSON as an Int and other times it will return that same key as a String. How do I use codable to parse that JSON? struct GeneralProduct: Codable { var price:Double! var id:String? var name:String! private enum CodingKeys: String, CodingKey { case price = \"p\" case id = \"i\" case name = \"n\" } init(price:Double? = nil, id: String? = nil, name: String? = nil) { self.price = price self.id = id self.name = name }

How to convert a date string with optional fractional seconds using Codable in Swift4

白昼怎懂夜的黑 提交于 2019-11-26 05:16:09
I am replacing my old JSON parsing code with Swift's Codable and am running into a bit of a snag. I guess it isn't as much a Codable question as it is a DateFormatter question. Start with a struct struct JustADate: Codable { var date: Date } and a json string let json = """ { "date": "2017-06-19T18:43:19Z" } """ now lets decode let decoder = JSONDecoder() decoder.dateDecodingStrategy = .iso8601 let data = json.data(using: .utf8)! let justADate = try! decoder.decode(JustADate.self, from: data) //all good But if we change the date so that it has fractional seconds, for example: let json = """ {

How to decode a property with type of JSON dictionary in Swift 4 decodable protocol

假如想象 提交于 2019-11-26 04:08:42
问题 Let\'s say I have Customer data type which contains a metadata property that can contains any JSON dictionary in the customer object struct Customer { let id: String let email: String let metadata: [String: Any] } { \"object\": \"customer\", \"id\": \"4yq6txdpfadhbaqnwp3\", \"email\": \"john.doe@example.com\", \"metadata\": { \"link_id\": \"linked-id\", \"buy_count\": 4 } } The metadata property can be any arbitrary JSON map object. Before I can cast the property from a deserialized JSON from