2014-09-30 82 views
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]; 
     } 
    }]; 
} 

回答

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; 
} 
5

您可以通過修改JSONKeyPathsByPropertyKey方法傳遞類型的信息:在contentJSONTransformer

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

然後,您可以訪問 「類型」 屬性:

+ (NSValueTransformer *)contentJSONTransformer 
{ 
    return [MTLValueTransformer ... 
     ... 
     NSString *type = value[@"type"]; 
     id content = value[@"content"]; 
    ]; 
} 
+0

這是完美的解決方案!謝謝。許多問題已經解決。 – CFIFok 2016-05-27 08:35:57

相關問題