2

私のアプリは、JSON からいくつかの ObJC オブジェクトを作成します。JSON に対応するものがない ObjC モデル クラスに新しいプロパティを追加するまで、問題なく動作していました。

次のようにマッピングを構成しました。

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

ただし、Mantle で次のようなアサーション エラーが発生MTLJSONAdapter initWithModelClassます

これは、モデル オブジェクトを作成する方法です。

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

phoneNumberJSON値にマッピングせずにデータクラスにプロパティを含めるにはどうすればよいですか?

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 に答える