简体   繁体   English

忽略JSON中的键

[英]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: 假设json包含:

{
    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". 问题是我收到一条错误消息:“此类不符合密钥prop2的键值编码标准”。

I also noticed that the JSONKeyPathsByPropertyKey method is not called when initialising the model with a dictionary try! super.init(dictionary: dictionaryValue, error: ()) 我还注意到,使用字典try! super.init(dictionary: dictionaryValue, error: ())初始化模型时,未调用JSONKeyPathsByPropertyKey方法try! super.init(dictionary: dictionaryValue, error: ()) try! super.init(dictionary: dictionaryValue, error: ()) , only when generating JSON from the model forcing the properties to have the same key as the JSON. try! super.init(dictionary: dictionaryValue, error: ()) ,仅当从模型生成JSON时强制属性具有与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. 我之所以希望能够忽略某些键,是因为后端服务可能会发生变化,并且由于调用中添加了一些额外的信息,或者它们根本不相关,因此我不必进行更新。

Turns out I wasn't using the MTLJSONAdapter , instead I was doing an init(dictionary: dictionaryValue, error: ()) . 原来我没有使用MTLJSONAdapter ,而是在做一个init(dictionary: dictionaryValue, error: ()) The correct way is to use MTLJSONAdapter.modelOfClass(MyClass.self, fromJSONDictionary: aDictionary, error: ()); 正确的方法是使用MTLJSONAdapter.modelOfClass(MyClass.self, fromJSONDictionary: aDictionary, error: ()); this way the JSONKeyPathsByPropertyKey method is in fact used. 这样,实际上就可以使用JSONKeyPathsByPropertyKey方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM