Skip to content


Subversion checkout URL

You can clone with
Download ZIP


Custom value transformer behavior #250

andrewjl opened this Issue · 3 comments

3 participants


Suppose I have a class with two properties:

@property (nonatomic, strong) NSArray *items;
@property (nonatomic, strong) NSString *listType;

where items is an array of objects that all have the same class.

Is it possible to create a JSON transformer for items that behaves along the lines of:

(NSValueTransformer*)itemsJSONTransformer {

    if([listType isEqualToString:kListTypeFoo]) {
        return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:[Foo class]]; 
    } else {
        return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:[Bar class]];


Wouldn't that depend on setting items and list in the correct order though? Not sure how many types of items there will be but what if you used a class cluster?

@interface XYList : NSObject

@property (readonly, nonatomic, copy) NSArray *items;


@interface XYFooList : XYList

@interface XYBarList : XYList

and then

@implementation XYList

#pragma mark - MTLJSONSerializing

+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return @{
        @"items": @"items"

+ (Class)classForParsingJSONDictionary:(NSDictionary *)dict {
    if ([dict[@"type"] isEqual:@"foo"]) return XYFooList.class;

    if ([dict[@"type"] isEqual:@"bar"]) return XYBarList.class;

    NSAssert(NO, @"Could not resolve class for %@", dict);
    return nil;


@implementation XYFooList

+ (NSValueTransformer *)itemsJSONTransformer {
  return [NSValueTransformer mtl_JSONArrayTransformerWithModelClass:XYFoo.class];


If you end up having a lot of types, doing this through meta-programming may make sense.


:+1: on a class cluster for solving this sort of problem.


Tentatively closing this one then, feel free to reopen if you have any further questions!

@robb robb closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.