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,您可以访问“类型”属性:

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

我遇到了类似的问题,我怀疑我的解决方案并不比你的好。

我的 Mantle 对象有一个通用的基类,在构造每个对象后,我调用一个配置方法,让它们有机会设置依赖于多个“基”(== 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 回答