JSONModel Generic Class

173 views Asked by At

I'm currently trying to include JSONModel to a project I'm currently working on... In this project I need to get data from a web service, that always returns me same data structure, but with different entries... So I build a base JSONModel class that should work with all the responses. I looks like this:

@interface WebserviceResponse : JSONModel

@property (assign, nonatomic) BOOL success;
@property (assign, nonatomic) int code;
@property (strong, nonatomic) NSString *message;
@property (strong, nonatomic) NSString *timestamp;
@property (strong, nonatomic) NSArray *list;

@end

The data I get from the web service is always given in "list" and is always a dictionary (but it differs with the different API methods I call). Except on an error it is "null"...

How can I define this list property to simply parse the given dictionaries? With the given structure my object is always null :(

Thanks for your help, Urkman

1

There are 1 answers

0
Burrows Wang On

Try using BWJSONMatcher, declare your base response data model as follows:

@interface WebserviceResponse : NSObject<BWJSONValueObject>

@property (assign, nonatomic) BOOL success;
@property (assign, nonatomic) int code;
@property (strong, nonatomic) NSString *message;
@property (strong, nonatomic) NSString *timestamp;
@property (strong, nonatomic) NSArray *list;

@end

For each of your API, declare a response model that inherited from WebserviceResponse and override the function typeInProperty: in protocol BWJSONValueObject :

// APIDataModel is the corresponding data model in "list" of this api
- (Class)typeInProperty:(NSString *)property {
    if ([property isEqualToString:@"list"]) {
        return [APIDataModel class];
    }

    return nil;
}

Further detailed examples of how to use BWJSONMatcher can be found here.