Search code examples
iosobjective-cjsonmacosgithub-mantle

Serializing a nested data structure of MTLModel subclasses to JSON


I got a problem concerning the Mantle framework from Github. I want to do the following

@interface ClassA : MTLModel <MTLJSONSerializing>
@property(strong, non-atomic) ClassB *instanceOfB; 
@end

@implementation ClassA
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return [super.JSONKeyPathsByPropertyKey mtl_dictionaryByAddingEntriesFromDictionary:@{
            @"instanceOfB": @"user"
            }];
}

@interface ClassB : MTLModel <MTLJSONSerializing>
@property(strong, non-atomic) NSString *name; 
@end

@implementation ClassB
+ (NSDictionary *)JSONKeyPathsByPropertyKey {
    return [super.JSONKeyPathsByPropertyKey mtl_dictionaryByAddingEntriesFromDictionary:@{
            @"name": @"user_name"
            }];
}

edited

When I serialize an instance of ClassA to JSON using [NSJSONSerialization dataWithJSONObject:[MTLJSONAdaptor JSONDictionaryFromModel:instanceOfA] I would like to get the following JSON object with selected properties of B nested under the JSON key user:

{ user: {
           user_name: <value of class B's name property>
        }
}

I think one would have to walk down the tree of object relationship similar to what NSCoding does. I am wondering if this behavior is already implemented and I just cannot figure out how to use it or if I have to code it myself.

I am also having trouble to find a bit more of documentation about the mantle framework besides the readme file.


Solution

  • I ended up adding a custom userJSONTransformer to classA:

    + (NSValueTransformer *)userJSONTransformer
    {
        return [MTLValueTransformer reversibleTransformerWithBlock:^id(ClassB *b){
            return @{ @"user_name": b.name,
                    };
        }];
    }
    

    Now the correct nested data structure is generated.