来自JSON和Mantle的对象:忽略属性

时间:2015-07-09 00:01:29

标签: ios github-mantle

我的应用程序从JSON创建一些ObJC对象。事情进展顺利,直到我向我的ObjC模型类添加了一个新属性,该类没有JSON中的对应物。

我已按如下方式配置映射:

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return @{
             @"firstName"                   : @"firstname",
             @"middleName"                  : @"middlename",
             @"lastName"                    : @"lastname",
             // etc.
             @"phoneNumber"                 : NSNull.null // no JSON data for this one
             };
}

然而,在MTLJSONAdapter initWithModelClass中,我在Mantle中得到断言失败:“ phoneNumber必须映射到JSON密钥路径或JSON密钥路径数组,得到:null。”< / p>

这就是我创建模型对象的方法:

MyData *myData = [MTLJSONAdapter modelOfClass:[MyData class] 
                           fromJSONDictionary:json error:&error];

如果数据类没有映射到JSON值,我怎么能拥有phoneNumber属性?

2 个答案:

答案 0 :(得分:4)

请勿指定其与+ JSONKeyPathsByPropertyKey的映射。

答案 1 :(得分:0)

accepted answer并没有最终为我工作(我没有从JSON对象解析),我发现子类化encodingBehaviorsByPropertyKey起作用。头文件中的注释如下:

/// Determines how the +propertyKeys of the class are encoded into an archive.
/// The values of this dictionary should be boxed MTLModelEncodingBehavior
/// values.
///
/// Any keys not present in the dictionary will be excluded from the archive.
///
/// Subclasses overriding this method should combine their values with those of
/// `super`.
///
/// Returns a dictionary mapping the receiver's +propertyKeys to default encoding
/// behaviors. If a property is an object with `weak` semantics, the default
/// behavior is MTLModelEncodingBehaviorConditional; otherwise, the default is
/// MTLModelEncodingBehaviorUnconditional.
+ (NSDictionary *)encodingBehaviorsByPropertyKey;

从我的MTLModel子类中覆盖该方法,最终为我工作:

+ (NSDictionary *)encodingBehaviorsByPropertyKey {
    NSMutableDictionary *encodingBehaviorsDictionary = [[super encodingBehaviorsByPropertyKey] mutableCopy];
    [encodingBehaviorsDictionary removeObjectForKey:@"propertyToBeOmitted"];
    return encodingBehaviorsDictionary;
}

仅供参考:我使用的是Mantle 2.1版。