pj4*_*533 7 json objective-c ios github-mantle
如何使用Github Mantle根据同一类中的另一个属性选择属性类?(或者更坏的情况是JSON对象的另一部分).
例如,如果我有这样的对象:
{
"content": {"mention_text": "some text"},
"created_at": 1411750819000,
"id": 600,
"type": "mention"
}
Run Code Online (Sandbox Code Playgroud)
我想做一个像这样的变压器:
+(NSValueTransformer *)contentJSONTransformer {
return [MTLValueTransformer transformerWithBlock:^id(NSDictionary* contentDict) {
return [MTLJSONAdapter modelOfClass:ETMentionActivityContent.class fromJSONDictionary:contentDict error:nil];
}];
}
Run Code Online (Sandbox Code Playgroud)
但传递给变换器的字典只包含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];
}
}];
}
Run Code Online (Sandbox Code Playgroud)
您可以通过修改JSONKeyPathsByPropertyKey方法来传递类型信息:
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
return @{
NSStringFromSelector(@selector(content)) : @[ @"type", @"content" ],
};
}
Run Code Online (Sandbox Code Playgroud)
然后contentJSONTransformer,您可以访问"type"属性:
+ (NSValueTransformer *)contentJSONTransformer
{
return [MTLValueTransformer ...
...
NSString *type = value[@"type"];
id content = value[@"content"];
];
}
Run Code Online (Sandbox Code Playgroud)
我也遇到过类似的问题,我怀疑我的解决方案并不比你的好多少。
我的 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1162 次 |
| 最近记录: |