0

我在将 JSON 数组转换为模型时遇到了一个问题。我正在使用JSONModel图书馆。

@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

这里templates数组可以同时具有PTProfileTemplateModelPTCategoryTemplateModel

JSON 输入:

{"title":"Core","templates":[{"type":0,"templateID":"","logoURL":"", "title":"data"},{"type":1,"templateID":"","category":"DB"}]}

我需要的是根据type我必须得到CategoryTemplateProfileTemplate。但在转换后,我得到的只是PTTemplateModel类型。

我知道我已将协议类型指定为PTTemplateModel. 但是如何根据给定的数据获得不同类型的模型。

我试过了:

  1. @property (nonatomic, strong) NSArray< PTTemplateModel>* templates;

  2. @property (nonatomic, strong) NSArray<PTProfileTemplateModel, PTCategoryTemplateModel>* templates;

  3. @property (nonatomic, strong) NSArray< PTTemplateModel , PTProfileTemplateModel, PTCategoryTemplateModel>* templates;

它们都不起作用。

有什么建议么?

4

1 回答 1

1

为什么不试试BWJSONMatcher,它可以帮助您以一种非常简洁的方式处理 json 数据:

@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

PTModel的实现中,实现协议 BWJSONValueObject 中声明函数typeInProperty ::

- (Class)typeInProperty:(NSString *)property {
    if ([property isEqualToString:@"templates"]) {
        return [PTTemplateModel class];
    }

    return nil;
}

然后您可以使用BWJSONMatcher在一行中获取您的数据模型:

PTModel *model = [PTModel fromJSONString:jsonString];

可以在此处找到如何使用BWJSONMatcher的详细示例。

于 2015-11-10T08:16:13.267 回答