How can I use Github Mantle to choose a property class based on another property in the same class? (or in the worse case another part of the JSON object).
For example if i have an object like this:
{
  "content": {"mention_text": "some text"},
  "created_at": 1411750819000,
  "id": 600,
  "type": "mention"
}
I want to make a transformer like this:
+(NSValueTransformer *)contentJSONTransformer {
    return [MTLValueTransformer transformerWithBlock:^id(NSDictionary* contentDict) {
          return [MTLJSONAdapter modelOfClass:ETMentionActivityContent.class fromJSONDictionary:contentDict error:nil];
    }];
}
But the dictionary passed to the transformer only includes the 'content' piece of the JSON, so I don't have access to the 'type' field. Is there anyway to access the rest of the object? Or somehow base the model class of 'content' on the 'type'?
I have previously been forced to do hack solutions like this:
+(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];
        }
    }];
}
                You can pass the type information by modifying the JSONKeyPathsByPropertyKey method:
+ (NSDictionary *)JSONKeyPathsByPropertyKey
{
    return @{
        NSStringFromSelector(@selector(content)) : @[ @"type", @"content" ],
    };
}
Then in contentJSONTransformer, you can access the "type" property:
+ (NSValueTransformer *)contentJSONTransformer 
{
    return [MTLValueTransformer ...
        ...
        NSString *type = value[@"type"];
        id content = value[@"content"];
    ];
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With