7

Github Mantle を使用して、同じクラスの別のプロパティに基づいてプロパティ クラスを選択するにはどうすればよいですか? (または最悪の場合、JSON オブジェクトの別の部分)。

たとえば、次のようなオブジェクトがある場合:

{
  "content": {"mention_text": "some text"},
  "created_at": 1411750819000,
  "id": 600,
  "type": "mention"
}

私はこのようなトランスフォーマーを作りたいです:

+(NSValueTransformer *)contentJSONTransformer {
    return [MTLValueTransformer transformerWithBlock:^id(NSDictionary* contentDict) {
          return [MTLJSONAdapter modelOfClass:ETMentionActivityContent.class fromJSONDictionary:contentDict error:nil];
    }];
}

しかし、トランスフォーマーに渡される辞書には JSON の「コンテンツ」部分しか含まれていないため、「タイプ」フィールドにはアクセスできません。オブジェクトの残りの部分にアクセスする方法はありますか? または、何らかの方法で「コンテンツ」のモデル クラスを「タイプ」に基づいていますか?

私は以前、次のようなハック ソリューションを行うことを余儀なくされました。

+(NSValueTransformer *)contentJSONTransformer {
    return [MTLValueTransformer transformerWithBlock:^id(NSDictionary* contentDict) {
        if (contentDict[@"mention_text"]) {
            return [MTLJSONAdapter modelOfClass:ETMentionActivityContent.class fromJSONDictionary:contentDict error:nil];
        } else {
            return [MTLJSONAdapter modelOfClass:ETActivityContent.class fromJSONDictionary:contentDict error:nil];
        }
    }];
}
4

2 に答える 2

5

JSONKeyPathsByPropertyKeyメソッドを変更して型情報を渡すことができます。

+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return @{
        NSStringFromSelector(@selector(content)) : @[ @"type", @"content" ],
    };
}

次にcontentJSONTransformer、「type」プロパティにアクセスできます。

+ (NSValueTransformer *)contentJSONTransformer 
{
    return [MTLValueTransformer ...
        ...
        NSString *type = value[@"type"];
        id content = value[@"content"];
    ];
}
于 2015-12-18T21:06:31.700 に答える
0

同様の問題がありましたが、私の解決策はあなたの解決策よりも優れているとは思えません。

Mantle オブジェクトに共通の基本クラスがあり、それぞれが構築された後、configure メソッドを呼び出して、複数の「基本」(== JSON) プロパティに依存するプロパティを設定する機会を与えます。

このような:

+(id)entityWithDictionary:(NSDictionary*)dictionary {

    NSError* error = nil;
    Class derivedClass = [self classWithDictionary:dictionary];
    NSAssert(derivedClass,@"entityWithDictionary failed to make derivedClass");
    HVEntity* entity = [MTLJSONAdapter modelOfClass:derivedClass fromJSONDictionary:dictionary error:&error];
    NSAssert(entity,@"entityWithDictionary failed to make object");
    entity.raw = dictionary;
    [entity configureWithDictionary:dictionary]; // Give the new entity a chance to set up derived properties
    return entity;
}
于 2015-06-24T12:49:31.700 に答える