2

我的应用程序从 JSON 创建了一些 ObJC 对象。一切正常,直到我向我的 ObjC 模型类添加了一个新属性,该属性在 JSON 中没有对应项。

我已将映射配置如下:

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

但是,我在 Mantle 中遇到断言失败MTLJSONAdapter initWithModelClass:“ phoneNumber 必须映射到 JSON 键路径或键路径的 JSON 数组,得到:null。

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

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

phoneNumber如果没有映射到 JSON 值,如何在数据类中拥有该属性?

4

2 回答 2

4

只是不要指定其映射到+ JSONKeyPathsByPropertyKey.

于 2015-07-09T00:15:56.673 回答
0

接受的答案最终没有为我工作(我没有从 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 版。

于 2016-12-19T06:46:54.527 回答