Reputation: 162
I have one problem in converting JSON array to model. I am using JSONModel
library.
@protocol PTTemplateModel <NSObject>
@end
@protocol PTProfileTemplateModel <PTTemplateModel>
@end
@protocol PTCategoryTemplateModel <PTTemplateModel>
@end
@interface PTTemplateModel : JSONModel
@property (nonatomic, assign) TemplateType type;
@property (nonatomic, copy) NSString* templateID;
@end
@interface PTProfileTemplateModel : PTTemplateModel
@property (nonatomic, copy) NSString* logoURL;
@property (nonatomic, copy) NSString* title;
@end
@interface PTCategoryTemplateModel : PTTemplateModel
@property (nonatomic, strong) NSString* category;
@end
@interface PTModel : JSONModel
@property (nonatomic, copy) NSString* title;
@property (nonatomic, strong) NSArray< PTTemplateModel>* templates; // PTTemplateModel
Here templates
array can have both PTProfileTemplateModel
and PTCategoryTemplateModel
.
JSON Input:
{"title":"Core","templates":[{"type":0,"templateID":"","logoURL":"", "title":"data"},{"type":1,"templateID":"","category":"DB"}]}
What I need is according to type
I have to get CategoryTemplate
or ProfileTemplate
. But after conversion I am getting just PTTemplateModel
type.
I know that I have specified protocol type as PTTemplateModel
. But how do I get different type of model according to given data.
I tried:
@property (nonatomic, strong) NSArray< PTTemplateModel>* templates;
@property (nonatomic, strong) NSArray<PTProfileTemplateModel, PTCategoryTemplateModel>* templates;
@property (nonatomic, strong) NSArray< PTTemplateModel , PTProfileTemplateModel, PTCategoryTemplateModel>* templates;
None of them works.
Any suggestions?
Upvotes: 0
Views: 284
Reputation: 249
Why not try BWJSONMatcher, it helps you work with json data in a very very neat way:
@interface PTModel : NSObject<BWJSONValueObject>
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSArray *templates;
@end
@interface PTTemplateModel : NSObject
@property (nonatomic, assign) TemplateType type;
@property (nonatomic, strong) NSString *templateID;
@property (nonatomic, strong) NSString *logoURL;
@property (nonatomic, strong) NSString *title;
@property (nonatomic, strong) NSString *category;
@end
In the implementation of PTModel, implement the function typeInProperty: declared in protocol BWJSONValueObject:
- (Class)typeInProperty:(NSString *)property {
if ([property isEqualToString:@"templates"]) {
return [PTTemplateModel class];
}
return nil;
}
Then you can use BWJSONMatcher to get your data model within one line:
PTModel *model = [PTModel fromJSONString:jsonString];
Detailed examples of how to use BWJSONMatcher can be found here.
Upvotes: 1