地幔忽略JSON中的键(Mantle ignore key in JSON)

系统教程 行业动态 更新时间:2024-06-14 16:59:22
地幔忽略JSON中的键(Mantle ignore key in JSON)

在创建我的地幔模型时,我一直试图忽略字典中的一个键。 让我们说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.

更多推荐

本文发布于:2023-04-16 19:08:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/bf4827543ab3ef500bcf8245521e02aa.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:地幔   JSON   Mantle   ignore   key

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!