codable

How can I implement polymorphic decoding of JSON data in Swift 4?

女生的网名这么多〃 提交于 2019-12-04 10:40:41
问题 I am attempting to render a view from data returned from an API endpoint. My JSON looks (roughly) like this: { "sections": [ { "title": "Featured", "section_layout_type": "featured_panels", "section_items": [ { "item_type": "foo", "id": 3, "title": "Bisbee1", "audio_url": "http://example.com/foo1.mp3", "feature_image_url" : "http://example.com/feature1.jpg" }, { "item_type": "bar", "id": 4, "title": "Mortar8", "video_url": "http://example.com/video.mp4", "director" : "John Smith", "feature

Swift Codable init

懵懂的女人 提交于 2019-12-04 07:16:45
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 Codable kicks in: init(id: Int, name: String) { // This initializer is not called if Decoded from JSON!

Ordered List With Core Data

十年热恋 提交于 2019-12-04 06:53:57
问题 I am working with a class which is both NSManagedObject and Codable . It's a Feed and it has multiple Albums . I want the ordered list of Albums but Core Data forces me to use Set instead, which is not ordered. I can use NSOrderedSet , but it doesn't work well with Codable . What would be the best way to get the ordered list in Core Data. Below is the Model I am trying to make work. public class Feed: NSManagedObject, Codable { @nonobjc public class func fetchRequest() -> NSFetchRequest<Feed>

Failable Initializers with Codable

荒凉一梦 提交于 2019-12-04 06:08:57
问题 I'm attempting to parse the following json schema of array of items, itemID may not be empty. How do I make an item nil id itemID does not exist in the JSON? [{ "itemID": "123", "itemTitle": "Hello" }, {}, ... ] My decodable classes are as follows: public struct Item: : NSObject, Codable { let itemID: String let itemTitle: String? } private enum CodingKeys: String, CodingKey { case itemID case itemTitle } required init(from decoder: Decoder) throws { let container = try decoder.container

Conforming NSAttributedString to Codable throws error

一曲冷凌霜 提交于 2019-12-04 04:59:49
问题 I need write and read NSAttributedString data into a json file, using this previously answered question I can encode the it but it throws an error while decoding. class AttributedString : Codable { let attributedString : NSAttributedString init(attributedString : NSAttributedString) { self.attributedString = attributedString } public required init(from decoder: Decoder) throws { let singleContainer = try decoder.singleValueContainer() let base64String = try singleContainer.decode(String.self)

Codable/Decodable should decode Array with Strings

蹲街弑〆低调 提交于 2019-12-04 03:50:13
问题 Why is the names Array not decoding? Prepared for Playground, Simple paste this into your playground import Foundation struct Country : Decodable { enum CodingKeys : String, CodingKey { case names } var names : [String]? } extension Country { public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) names = try values.decode([String]?.self, forKey: .names)! } } let json = """ [{ "names": [ "Andorre", "Andorra", "アンドラ" ] },{ "names": [ "United

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

拈花ヽ惹草 提交于 2019-12-04 01:42:10
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 = .convertFromSnakeCase let decoded = try decoder.decode(StudentInfo.self, from: Data(jsonString.utf8))

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

这一生的挚爱 提交于 2019-12-03 22:48:18
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(Error) } func checkStar(for userId: Int, completion: ((Result<check>) -> Void)?) { var urlComponents =

Create codable struct with generic type

本小妞迷上赌 提交于 2019-12-03 17:54:07
问题 First of all, Sorry for unclear title of question I'm making a codable struct which will be used as json message. enum MessageType: String, Codable{ case content case request case response } struct Message: Codable{ var type: MessageType var content: /* NEED HELP HERE */ } struct Content: Codable {...} struct Request: Codable {...} struct Response: Codable {...} When declaring Message , if its type is content , its content 's type should be Content . let message = Message( type: .content,

Swift 4 Decodable: struct from nested array

本小妞迷上赌 提交于 2019-12-03 16:11:45
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 the nested nodes container within the actors property from the JSON object. PlacerholderData: struct