swiftmodelmappinggithub-mantlemodelmapper

Mantle ignore key in JSON


I've been trying to ignore a key inside a dictionary when creating my mantle model. Let's say that the json contains:

{
    prop1:"my prop",
    prop2:"my prop2"
}

initially I have a model with

class MyModel: MTLModel, MTLJSONSerializing {


    //MARK: Model properties

    var prop1: String!

    class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! {

        return ["prop1":"prop1"]
    }
}

The problem is that I get an error saying " this class is not key value coding-compliant for the key prop2".

I also noticed that the JSONKeyPathsByPropertyKey method is not called when initialising the model with a dictionary try! super.init(dictionary: dictionaryValue, error: ()), only when generating JSON from the model forcing the properties to have the same key as the JSON. The reason why I want to be able to ignore certain keys is because the backend service might change and I don't necessarily HAVE to roll an update because some extra info has been added to the call or because they simply are completely irrelevant.


Solution

  • Turns out I wasn't using the MTLJSONAdapter, instead I was doing an init(dictionary: dictionaryValue, error: ()). The correct way is to use MTLJSONAdapter.modelOfClass(MyClass.self, fromJSONDictionary: aDictionary, error: ()); this way the JSONKeyPathsByPropertyKey method is in fact used.