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.

有帮助吗?

解决方案

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.

其他提示

You may use NSValueTransformer reverseTransformedValue method.

+ (NSValueTransformer *)userJSONTransformer
{
    return [MTLValueTransformer reversibleTransformerWithBlock:^id(ClassB *b){
        return [[NSValueTransformer mtl_JSONDictionaryTransformerWithModelClass:[ClassB class]] reverseTransformedValue:b]
    }];
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top