codable

How to use swift 4 Codable in Core Data?

情到浓时终转凉″ 提交于 2019-11-26 03:27: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

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

北城余情 提交于 2019-11-26 00:48:54
问题 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,

How do I use custom keys with Swift 4's Decodable protocol?

有些话、适合烂在心里 提交于 2019-11-26 00:22:22
问题 Swift 4 introduced support for native JSON encoding and decoding via the Decodable protocol. How do I use custom keys for this? E.g., say I have a struct struct Address:Codable { var street:String var zip:String var city:String var state:String } I can encode this to JSON. let address = Address(street: \"Apple Bay Street\", zip: \"94608\", city: \"Emeryville\", state: \"California\") if let encoded = try? encoder.encode(address) { if let json = String(data: encoded, encoding: .utf8) { //