在创建我的地幔模型时,我一直试图忽略字典中的一个键。 让我们说json包含:
{ prop1:"my prop", prop2:"my prop2" }最初我有一个模特
class MyModel: MTLModel, MTLJSONSerializing { //MARK: Model properties var prop1: String! class func JSONKeyPathsByPropertyKey() -> [NSObject : AnyObject]! { return ["prop1":"prop1"] } }问题是我得到一个错误,说“这个类不是密钥值编码兼容的关键prop2”。
我还注意到,在使用字典初始化模型时,不会调用JSONKeyPathsByPropertyKey方法try! super.init(dictionary: dictionaryValue, error: ()) try! super.init(dictionary: dictionaryValue, error: ()) ,仅在从模型生成JSON时强制属性具有与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.
最满意答案
事实证明我没有使用MTLJSONAdapter ,而是在做一个init(dictionary: dictionaryValue, error: ()) 。 正确的方法是使用MTLJSONAdapter.modelOfClass(MyClass.self, fromJSONDictionary: aDictionary, error: ()); 这样就实际上使用了JSONKeyPathsByPropertyKey方法。
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.
更多推荐
发布评论