Codable [String: Any] dictionary [duplicate] - swift

This question already has answers here:
Swift - Encode and Decode a dictionary [String:Any] into plist
(2 answers)
Closed 3 years ago.
In my code I have a class with a property of type [String: Any]. On implementing the Codable protocol the compiler shows error that says
Protocol type 'Any' cannot conform to 'Decodable' because only concrete types can conform to protocols
open class MMSDKNotification: Codable {
enum MMSDKNotificationKeys: String, CodingKey { // declaring our keys
case id = "id"
case message = "message"
case isRead = "isRead"
case creationTime = "creationTime"
}
public var id: Int = 0
public var message: [String: Any]?
public var isRead: Bool = false
public var creationTime: Int = 0
required public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: MMSDKNotificationKeys.self) // defining our (keyed) container
self.id = try container.decode(Int.self, forKey: .id)
// Here is the error:
// Protocol type 'Any' cannot conform to 'Decodable' because only concrete types can conform to protocols
self.message = try container.decode(String.self, forKey: .type)
self.isRead = try container.decode(Bool.self, forKey: .isRead)
self.creationTime = try container.decode(Int.self, forKey: .creationTime)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: MMSDKNotificationKeys.self)
try container.encode(id, forKey: .id)
try container.encode(isRead, forKey: .isRead)
try container.encode(creationTime, forKey: .creationTime)
}
}
Is it possible to use Codable with [String: Any] dictionary?

Is it possible to use Codable with [String: Any] dictionary?
no, you can't with Codable but you can make this dictionary in a new model.
Replace
public var message: [String: Any]?
with
public var message: MessageModel?
struct MessageModel: Codable { }

Is it possible to use Codable with [String: Any] dictionary?
No you can't with Codable you have to explicitly write the type that should conform to Codable otherwise go with SwiftyJSON/JSONSerialization

Related

Trying to make this class codable and decodable

Trying to make this class codable and decodable
import Foundation
class Attribute : Decodable {
struct Att: Decodable {
var number: Int16
var label: String
var comments: String
// Everything from here on is generated for you by the compiler
init(from decoder: Decoder) throws {
let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
number = try keyedContainer.decode(Int16.self, forKey: .number)
label = try keyedContainer.decode(String.self, forKey: .label)
comments = try keyedContainer.decode(String.self, forKey: .comments)
}
enum CodingKeys: String, CodingKey {
case number
case label
case comments
}
}
}
extension Attribute: Encodable {
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(number, forKey: .number)
try container.encode(label, forKey: .label)
try container.encode(comments, forKey: .comments)
}
}
I have an error on these lines
try container.encode(number, forKey: .number)
try container.encode(label, forKey: .label)
try container.encode(comments, forKey: .comments)
with the message
Use of unresolved identifier 'number'
Use of unresolved identifier 'label'
Use of unresolved identifier 'comments'
How do I solve that?
Why do you have an empty class with a nested struct in it? The error comes from the fact that those properties are defined on Att rather than Attribute, so you need to encode those when extending Att to conform to Encodable.
Btw, you don't have any special encoding/decoding, so you don't need to declare the encoder/decoder functions manually, the compiler can synthesise them for you.
class Attribute: Codable {
struct Att: Codable {
var number: Int16
var label: String
var comments: String
}
}
I may have missed something, but the following should work, or at least compile:
class Attribute : Decodable {
var number: Int16
var label: String
var comments: String
// Everything from here on is generated for you by the compiler
required init(from decoder: Decoder) throws {

RLMArray in swift with decoder : Ambiguous reference to member error

I want to use Realm in mixed Objective-C & Swift app working with Codable and Realm Object can be export to Objective-C ;
class Person2 : RLMObject,Decodable {
#objc dynamic var name = ""
convenience init(_ name:String) {
self.init()
self.name = name
}
}
class RepairShop2 : RLMObject,Decodable {
#objc dynamic var name = ""
#objc dynamic var contact:Person2?
#objc dynamic var persons = RLMArray<Person2>(objectClassName: Person2.className())
private enum RepairShop2CodingKeys: String, CodingKey {
case name
case contact
case persons
}
convenience init(name: String, contact: Person2, persons: RLMArray<Person2>) {
self.init()
self.name = name
self.contact = contact
self.persons = persons
}
convenience required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: RepairShop2CodingKeys.self)
let name = try container.decode(String.self, forKey: .name)
let contact = try container.decode(Person2.self, forKey: .contact)
let personArray = try container.decode(RLMArray<AnyObject>, forKey: .persons)
// this line error: Ambiguous reference to member 'decode(_:forKey:)'**
let persons = RLMArray<Person2>(objectClassName: Person2.className())
persons.addObjects(personArray)
self.init(name: name, contact: contact, persons: persons)
}
}
let personArray = try container.decode(RLMArray<AnyObject>, forKey: .persons)
// this line error: Ambiguous reference to member 'decode(_:forKey:)'**
RLMArray.self I also tried , fail
how to write decode type of RLMArray?
RLMRealm doesn't conform to Decodable so you'll not be able to parse it into RLMRealm straight away. Instead try something like:
let persons = RLMArray<Person2>(objectClassName: Person2.className())
persons.addObjects(try container.decode([Person2].self, forKey: .persons) as NSFastEnumeration)
As a side note. Mixing different domains into one model is bad idea, it may bite later.

Store Encodables in a Swift Dictionary

I'm looking to store models objects in a Dictionary and would like to serialize the whole dictionary using JSONEncoder into data and subsequently into a string and save it.
The idea is to use Swift 4's out of the box Encodable to ensure anything that I add to the dictionary will be serialized which can include primitives and custom objects (which will themselves conform to Encodable).
The Challenge is what type should I declare the dictionary to be:
If I use [String: Any], it won't know how to encode Any, and if I have to cast it into an actual concrete type, it kind of defeats the purpose of generics
If I use [String: Encodable], it will crash at run time saying
Encodable doesn't conform to itself, which is understandable as it
needs a concrete type
In order to tackle this, I thought of creating a wrapper:
i.e A protocol with an associated type or a struct with generic type value:
struct Serializable<T: Encodable> {
var value: T?
init(value: T) {
self.value = value
}
}
But the problem remains, while declaring the type of the aforementioned dictionary, I still have to supply the concrete type..
var dictionary: [String: Serializable<X>]
What should 'X' be here, Or, what's the correct way to achieve this?
What am I missing?
Two possible approaches:
You can create dictionary whose values are Encodable wrapper type that simply encodes the underlying value:
struct EncodableValue: Encodable {
let value: Encodable
func encode(to encoder: Encoder) throws {
try value.encode(to: encoder)
}
}
Then you can do:
let dictionary = [
"foo": EncodableValue(value: Foo(string: "Hello, world!")),
"bar": EncodableValue(value: Bar(value: 42)),
"baz": EncodableValue(value: "qux")
]
let data = try! JSONEncoder().encode(dictionary)
You can define your own Codable type instead of using dictionary:
struct RequestObject: Encodable {
let foo: Foo
let bar: Bar
let baz: String
}
let requestObject = RequestObject(
foo: Foo(string: "Hello, world!"),
bar: Bar(value: 42),
baz: "qux"
)
let data = try! JSONEncoder().encode(requestObject)
Needless to say, these both assume that both Foo and Bar conform to Encodable.
This is my solution (improved by Rob answer):
struct EncodableValue: Encodable {
let value: Encodable
func encode(to encoder: Encoder) throws {
try value.encode(to: encoder)
}
}
struct Storage: Encodable {
var dict: [String: Encodable] = [:]
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
for (key, value) in dict {
guard let codingKey = CodingKeys(stringValue: key) else {
continue
}
if let enc = value as? EncodableValue {
try container.encode(enc, forKey: codingKey)
}
}
}
struct CodingKeys: CodingKey {
var stringValue: String
init?(stringValue: String) {
self.stringValue = stringValue
}
var intValue: Int?
init?(intValue: Int) {
return nil
}
}
}
let dict: [String: EncodableValue] = ["test": EncodableValue(value:1), "abc":EncodableValue(value:"GOGO")]
let storage = Storage(dict: dict)
do {
let data = try JSONEncoder().encode(storage)
let res = String(data: data, encoding: .utf8)
print(res ?? "nil")
} catch {
print(error)
}

`RLMArray` does not conform to protocol 'Encodable'

I want to Do:
Using JSONDecoder(), I convert json to Realm object.
And I save this object to Realm databases.
Problem:
RLMArray don't apply Codable protocol.
I could be conformed Decodable protocol, but Codable I couldn't.
Error Message:
Type 'Person' does not conform to protocol 'Encodable'
Code:
public class Hobby: Object, Codable {
#objc dynamic var title: String?
#objc dynamic var category: String?
}
public class Person: Object, Codable { // Error: Type 'Person' does not conform to protocol 'Encodable'
#objc dynamic var name: String?
#objc dynamic var hobbies: RLMArray<Hobby>?
required convenience public init(from decoder: Decoder) throws {
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decode(String.self, forKey: .name)
hobbies = try container.decode(RLMArray<Hobby>?.self, forKey: .hobbies)
}
}
func sample() {
let person = try? JSONDecoder().decode(Person.self, from: "{\"name\" : \"aaa\",\"hobbies\" : [{\"title\" : \"fishing\",\"category\" : \"outdoor\"},{\"title\" : \"reading\",\"type\" : \"indoor\"}]}".data(using: .utf8)!)
print(person)
let realm = try! Realm()
try! realm.write {
realm.add(person!)
}
}
Do you have some ideas?
Swift4
RealmSwift
Codable is the exact same as Decodable + Encodable. If you want to conform to Codable you will need to implement the encoding functions, which for your Person object would be:
enum CodingKeys: String, CodingKey {
case name
case hobbies
// or: case hobbies = "customHobbiesKey" if you want to encode to a different key
}
func encode(to encoder: Encoder) throws {
do {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(hobbies, forKey: .hobbies)
} catch {
print(error)
}
}
Add this to your Person class, and then implement the same thing for your Hobby class.
Because i'm not sure if you even want to encode: If all you need to do is create Realm-Objects from Json I would simply replace 'Codable' with the'Decodable'-Protocol.
EDIT: I noticed the issue is about the RLMArray. I'm not sure how codable works with RLMArray, but if it doesn't work you could try replacing the declaration with
let hobbies = List<Hobby>()
and then in init() replace the 'hobbies' line with:
let tempHobbyList: [Hobby] = try container.decode([Hobby].self, forKey: .hobbies)
self.hobbies.append(objectsIn: tempHobbyList)
That's how I got my lists with realmObjects to work with codable

How to implement Codable in a custom subclass (Swift 4) [duplicate]

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 Development : Server, Codable {
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")
output is:
id is nil
Large Building Development
And you can't express Codable in both classes.
I believe in the case of inheritance you must implement Coding yourself. That is, you must specify CodingKeys and implement init(from:) and encode(to:) in both superclass and subclass. Per the WWDC video (around 49:28, pictured below), you must call super with the super encoder/decoder.
required init(from decoder: Decoder) throws {
// Get our container for this subclass' coding keys
let container = try decoder.container(keyedBy: CodingKeys.self)
myVar = try container.decode(MyType.self, forKey: .myVar)
// otherVar = ...
// Get superDecoder for superclass and call super.init(from:) with it
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
}
The video seems to stop short of showing the encoding side (but it's container.superEncoder() for the encode(to:) side) but it works in much the same way in your encode(to:) implementation. I can confirm this works in this simple case (see playground code below).
I'm still struggling with some odd behavior myself with a much more complex model I'm converting from NSCoding, which has lots of newly-nested types (including struct and enum) that's exhibiting this unexpected nil behavior and "shouldn't be". Just be aware there may be edge cases that involve nested types.
Edit: Nested types seem to work fine in my test playground; I now suspect something wrong with self-referencing classes (think children of tree nodes) with a collection of itself that also contains instances of that class' various subclasses. A test of a simple self-referencing class decodes fine (that is, no subclasses) so I'm now focusing my efforts on why the subclasses case fails.
Update June 25 '17: I ended up filing a bug with Apple about this. rdar://32911973 - Unfortunately an encode/decode cycle of an array of Superclass that contains Subclass: Superclass elements will result in all elements in the array being decoded as Superclass (the subclass' init(from:) is never called, resulting in data loss or worse).
//: Fully-Implemented Inheritance
class FullSuper: Codable {
var id: UUID?
init() {}
private enum CodingKeys: String, CodingKey { case id }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(UUID.self, forKey: .id)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(id, forKey: .id)
}
}
class FullSub: FullSuper {
var string: String?
private enum CodingKeys: String, CodingKey { case string }
override init() { super.init() }
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let superdecoder = try container.superDecoder()
try super.init(from: superdecoder)
string = try container.decode(String.self, forKey: .string)
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(string, forKey: .string)
let superencoder = container.superEncoder()
try super.encode(to: superencoder)
}
}
let fullSub = FullSub()
fullSub.id = UUID()
fullSub.string = "FullSub"
let fullEncoder = PropertyListEncoder()
let fullData = try fullEncoder.encode(fullSub)
let fullDecoder = PropertyListDecoder()
let fullSubDecoded: FullSub = try fullDecoder.decode(FullSub.self, from: fullData)
Both the super- and subclass properties are restored in fullSubDecoded.
Found This Link - Go down to inheritance section
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(employeeID, forKey: .employeeID)
}
For Decoding I did this:
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let values = try decoder.container(keyedBy: CodingKeys.self)
total = try values.decode(Int.self, forKey: .total)
}
private enum CodingKeys: String, CodingKey
{
case total
}
🚀 Swift introduced Property Wrappers in 5.1 I implemented a library called SerializedSwift that uses the power of property wrappers to Decode and Encode JSON data to objects.
One of my main goals was, to make inherited object to decode out of the box, without additonal init(from decoder: Decoder) overrides.
import SerializedSwift
class User: Serializable {
#Serialized
var name: String
#Serialized("globalId")
var id: String?
#Serialized(alternateKey: "mobileNumber")
var phoneNumber: String?
#Serialized(default: 0)
var score: Int
required init() {}
}
// Inherited object
class PowerUser: User {
#Serialized
var powerName: String?
#Serialized(default: 0)
var credit: Int
}
It also supports custom coding keys, alternate keys, default values, custom transformation classes and many more features to be included in the future.
Available on GitHub (SerializedSwift).
I was able to make it work by making my base class and subclasses conform to Decodable instead of Codable. If I used Codable it would crash in odd ways, such as getting a EXC_BAD_ACCESS when accessing a field of the subclass, yet the debugger could display all the subclass values with no problem.
Additionally, passing the superDecoder to the base class in super.init() didn't work. I just passed the decoder from the subclass to the base class.
How about using the following way?
protocol Parent: Codable {
var inheritedProp: Int? {get set}
}
struct Child: Parent {
var inheritedProp: Int?
var title: String?
enum CodingKeys: String, CodingKey {
case inheritedProp = "inherited_prop"
case title = "short_title"
}
}
Additional info on composition: http://mikebuss.com/2016/01/10/interfaces-vs-inheritance/
Here is a library TypePreservingCodingAdapter to do just that (can be installed with Cocoapods or SwiftPackageManager).
The code below compiles and works just fine with Swift 4.2. Unfortunately for every subclass you'll need to implement encoding and decoding of properties on your own.
import TypePreservingCodingAdapter
import Foundation
// redeclared your types with initializers
class Server: Codable {
var id: Int?
init(id: Int?) {
self.id = id
}
}
class Development: Server {
var name: String?
var userId: Int?
private enum CodingKeys: String, CodingKey {
case name
case userId
}
init(id: Int?, name: String?, userId: Int?) {
self.name = name
self.userId = userId
super.init(id: id)
}
required init(from decoder: Decoder) throws {
try super.init(from: decoder)
let container = try decoder.container(keyedBy: CodingKeys.self)
name = try container.decodeIfPresent(String.self, forKey: .name)
userId = try container.decodeIfPresent(Int.self, forKey: .userId)
}
override func encode(to encoder: Encoder) throws {
try super.encode(to: encoder)
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(name, forKey: .name)
try container.encode(userId, forKey: .userId)
}
}
// create and adapter
let adapter = TypePreservingCodingAdapter()
let encoder = JSONEncoder()
let decoder = JSONDecoder()
// inject it into encoder and decoder
encoder.userInfo[.typePreservingAdapter] = adapter
decoder.userInfo[.typePreservingAdapter] = adapter
// register your types with adapter
adapter.register(type: Server.self).register(type: Development.self)
let server = Server(id: 1)
let development = Development(id: 2, name: "dev", userId: 42)
let servers: [Server] = [server, development]
// wrap specific object with Wrap helper object
let data = try! encoder.encode(servers.map { Wrap(wrapped: $0) })
// decode object back and unwrap them force casting to a common ancestor type
let decodedServers = try! decoder.decode([Wrap].self, from: data).map { $0.wrapped as! Server }
// check that decoded object are of correct types
print(decodedServers.first is Server) // prints true
print(decodedServers.last is Development) // prints true
Swift 5
The compiler synthesises decodable code only for a type that directly adopts Codable protocol so that you observe decoding for a single of your type in inheritance.
But you can try next generic approach with KeyValueCoding package (https://github.com/ikhvorost/KeyValueCoding) and this package provides access to all properties metadata and allows to get/set any property for pure swift types dynamically. The idea is to make a base Coding class which adopts KeyValueCoding and implements decoding of all available properties in init(from: Decoder):
class Coding: KeyValueCoding, Decodable {
typealias DecodeFunc = (KeyedDecodingContainer<_CodingKey>, _CodingKey) throws -> Any?
struct _CodingKey: CodingKey {
let stringValue: String
let intValue: Int?
init(stringValue: String) {
self.stringValue = stringValue
self.intValue = Int(stringValue)
}
init(intValue: Int) {
self.stringValue = "\(intValue)"
self.intValue = intValue
}
}
static func decodeType<T: Decodable>(_: T.Type) -> (type: T.Type, f: DecodeFunc) {
(T.self, { try $0.decode(T.self, forKey: $1) })
}
static var decodeTypes: [(Any.Type, DecodeFunc)] = [
decodeType(Int.self),
decodeType(Int?.self),
decodeType(String.self),
decodeType(String?.self),
// Other types to support...
]
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: _CodingKey.self)
try container.allKeys.forEach { codingKey in
let key = codingKey.stringValue
guard let property = (properties.first { $0.name == key }),
let item = (Self.decodeTypes.first { property.type == $0.0 })
else {
return
}
var this = self
this[key] = try item.1(container, codingKey)
}
}
}
It is important to provide all supported types to decode in decodeTypes variable.
How to use:
class Server: Coding {
var id: Int?
}
class Development : Server {
var name: String = ""
}
class User: Development {
var userId: Int = 0
}
func decode() {
let json = "{\"id\": 1, \"name\": \"Large Building Development\", \"userId\": 123}"
do {
let user = try JSONDecoder().decode(User.self, from:json.data(using: .utf8)!)
print(user.id, user.name, user.userId) // Optional(1) Large Building Development 123
}
catch {
print(error.localizedDescription)
}
}