evermeer / EVReflection

Reflection based (Dictionary, CKRecord, NSManagedObject, Realm, JSON and XML) object mapping with extensions for Alamofire and Moya with RxSwift or ReactiveSwift
Other
965 stars 119 forks source link

ERROR: Could not create an instance for type Swift.Dictionary<Swift.String, Swift.Array<MyObject>> #293

Closed jayfray12 closed 6 years ago

jayfray12 commented 6 years ago

One JSON response that I have should be parsed as type Dictionary<String,Array<MyObject>>. I have successfully parsed this by overriding the setValue method like this:

override func setValue(_ value: Any!, forUndefinedKey key: String) { switch key { case "response": if let dict = value as? NSDictionary { response = Dictionary<String,Array<MyObject>>(); for (key, value) in dict { var listValues = Array<MyObject>(); if let array = value as? NSArray { for vd in array { listValues.append(MyObject(dictionary: vd as! NSDictionary)); } } response![key as? String ?? ""] = listValues; } } break; } }

However, I still get the Error message in the title. Is there a different way I should be doing this? How do I get the error to go away?

evermeer commented 6 years ago

The setValue forUndefinedKey is a fallback solution for handeling issues that can not be handled otherwise. I think that in your case it would be better to use a property converter. Below you can see a sample. It's not for a dictionary, but I think you can easily convert your code to this.


public class TestObject6: EVObject {
    var isGreat: Bool = false

    override func propertyConverters() -> [(key: String, decodeConverter: ((Any?) -> ()), encodeConverter: (() -> Any?))] {
        return [
            ( // We want a custom converter for the field isGreat
              key: "isGreat"
              // isGreat will be true if the json says 'Sure'
              , decodeConverter: { self.isGreat = ($0 as? String == "Sure") }
              // The json will say 'Sure  if isGreat is true, otherwise it will say 'Nah'
              , encodeConverter: { return self.isGreat ? "Sure": "Nah"})
        ]
    }
}
jayfray12 commented 6 years ago

Thanks that did the trick!