Mantle property class based on another property?

How can I use the Github Mantle to select a class of properties based on another property in the same class? (or in the worst 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 as follows:

 +(NSValueTransformer *)contentJSONTransformer { return [MTLValueTransformer transformerWithBlock:^id(NSDictionary* contentDict) { return [MTLJSONAdapter modelOfClass:ETMentionActivityContent.class fromJSONDictionary:contentDict error:nil]; }]; } 

But the dictionary passed to the transformer includes only part of the JSON content, so I don't have access to the type field. Is there any access to the rest of the facility? Or is it somehow based on the model class "content" on "type"?

Earlier I had to do such hacks:

 +(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]; } }]; } 
+7
json ios objective-c github-mantle
source share
2 answers

You can pass type information by changing 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"]; ]; } 
+5
source share

I had a similar problem and I suspect my solution is not much better than yours.

I have a common base class for Mantle objects, and after each construction I call the configure method to enable them to configure properties that depend on more than one base property (== JSON).

Like this:

 +(id)entityWithDictionary:(NSDictionary*)dictionary { NSError* error = nil; Class derivedClass = [self classWithDictionary:dictionary]; NSAssert(derivedClass,@"entityWithDictionary failed to make derivedClass"); HVEntity* entity = [MTLJSONAdapter modelOfClass:derivedClass fromJSONDictionary:dictionary error:&error]; NSAssert(entity,@"entityWithDictionary failed to make object"); entity.raw = dictionary; [entity configureWithDictionary:dictionary]; // Give the new entity a chance to set up derived properties return entity; } 
0
source share

All Articles