codable

Swift 4 Codable; How to decode object with single root-level key

梦想的初衷 提交于 2019-11-27 19:01:54
I'm using the Swift 4 Codable protocol with JSON data. My data is formatted such that there is a single key at the root level with an object value containing the properties I need, such as: { "user": { "id": 1, "username": "jdoe" } } I have a User struct that can decode the user key: struct User: Codable { let id: Int let username: String } Since id and username are properties of user , not at the root level, I needed to make a wrapper type like so: struct UserWrapper: Codable { let user: User } I can then decode the JSON via the UserWrapper , and the User is decoded also. It seems like a lot

How to conform UIImage to Codable?

老子叫甜甜 提交于 2019-11-27 17:37:12
问题 Swift 4 has Codable and it's awesome. But UIImage does not conform to it by default. How can we do that? I tried with singleValueContainer and unkeyedContainer extension UIImage: Codable { // 'required' initializer must be declared directly in class 'UIImage' (not in an extension) public required init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() let data = try container.decode(Data.self) guard let image = UIImage(data: data) else { throw MyError

Use swift Codable to decode JSON with values as keys

不羁岁月 提交于 2019-11-27 15:46:59
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" } } } } What do I have to fix in the Container & Drawer class to have the key as a title property and

Using JSONEncoder to encode a variable with Codable as type

天涯浪子 提交于 2019-11-27 14:17:01
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: Encodable, at location: String) { // Some code let data = try JSONEncoder().encode(object) // Some more code }

What is difference between optional and decodeIfPresent when using Decodable for JSON Parsing?

人盡茶涼 提交于 2019-11-27 12:25:51
I am using Codable protocol from Swift 4 first time, I am not able to understand use of decodeIfPresent from Decodable . /// Decodes a value of the given type for the given key, if present. /// /// This method returns `nil` if the container does not have a value associated with `key`, or if the value is null. The difference between these states can be distinguished with a `contains(_:)` call. /// /// - parameter type: The type of value to decode. /// - parameter key: The key that the decoded value is associated with. /// - returns: A decoded value of the requested type, or `nil` if the

How can I use Swift’s Codable to encode into a dictionary?

僤鯓⒐⒋嵵緔 提交于 2019-11-27 10:59:22
I have a struct that implements Swift 4’s Codable . Is there a simple built-in way to encode that struct into a dictionary? let struct = Foo(a: 1, b: 2) let dict = something(struct) // now dict is ["a": 1, "b": 2] Chris Mitchelmore If you don't mind a bit of shifting of data around you could use something like this: extension Encodable { func asDictionary() throws -> [String: Any] { let data = try JSONEncoder().encode(self) guard let dictionary = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as? [String: Any] else { throw NSError() } return dictionary } } Or an

How to use Any in Codable Type

喜夏-厌秋 提交于 2019-11-27 08:39:43
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. 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 your issue currently is to use generics like below. struct Person<T> { var id: T var name: String } let

Swift 4 JSON Decodable simplest way to decode type change

风流意气都作罢 提交于 2019-11-27 07:16:55
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 does that with a String based Float Otherwise I've been stuck with using CodingKey to bring in a String and use a

Swift 4 decode simple root level json value

喜欢而已 提交于 2019-11-27 06:44:41
问题 According to the JSON standard RFC 7159, this is valid json: 22 How do I decode this into an Int using swift4's decodable? This does not work let twentyTwo = try? JSONDecoder().decode(Int.self, from: "22".data(using: .utf8)!) 回答1: It works with good ol' JSONSerialization and the .allowFragments reading option. From the documentation: allowFragments Specifies that the parser should allow top-level objects that are not an instance of NSArray or NSDictionary. Example: let json = "22".data(using:

With JSONDecoder in Swift 4, can missing keys use a default value instead of having to be optional properties?

眉间皱痕 提交于 2019-11-27 06:24:13
Swift 4 added the new Codeable protocol. When I use JSONDecoder it seems to require all the non-optional properties of my Codeable class to have keys in the JSON or it throws an error. Making every property of my class optional seems like an unecessary hassle since what I really want is to use the value in the json or a default value. (I don't want the property to be nil.) Is there a way to do this? class MyCodable: Codable { var name: String = "Default Appleseed" } func load(input: String) { do { if let data = input.data(using: .utf8) { let result = try JSONDecoder().decode(MyCodable.self,