MantleFramework/Mantle — pull request #233 by dblock (2014-02-06 14:11:44+00:00)
Title: Added support for deserializing into different types based on JSON data itself.

Sometimes you want polymorphic behavior, but you don't want polymorphic types. The example below is a message that can be put in an envelope, but the only thing in common between a TCP/IP packet and a postcard is that they have a body. You only want them to implement a common protocol.

This extends `mtl_JSONDictionaryTransformerWithModelClass` with a `mtl_JSONDictionaryTransformerWithModelClassFrom` that takes a block that lets you decide what class to use for deserialization, dynamically. This way you can examine the data at runtime and, for example, return a type based on a "type" field of the JSON data itself.

``` objc
@protocol XYMessage
@property (nonatomic, copy, readonly) NSString *body;
@end

@interface XYTCPIPPacket
@property (nonatomic, copy, readonly) NSString *body;
@end

@interface XYPostcard
@property (nonatomic, copy, readonly) NSString *body;
@end

@interface XYEnvelope
@property (nonatomic, retain) id message;
@end

@implementation XYEnvelope

+ (NSValueTransformer *)messageJSONTransformer {
return [MTLValueTransformer mtl_JSONDictionaryTransformerWithModelClassFrom:^Class(id JSONDictionary) {
return NSClassFromString(JSONDictionary[@"type"]); // can be XYTCPIPPacket or XYPostcard
}];
}

@end
```