gpt4 book ai didi

ios - 使用 JSONModel 库将 jsonarray(具有不同类型)转换为模型数组

转载 作者:行者123 更新时间:2023-11-29 01:31:35 24 4
gpt4 key购买 nike

我在将 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类型。

我知道我已将协议(protocol)类型指定为 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;

它们都不起作用。

有什么建议吗?

最佳答案

为什么不试试 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的实现中,实现函数typeInProperty:在协议(protocol)BWJSONValueObject中声明:

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

return nil;
}

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

PTModel *model = [PTModel fromJSONString:jsonString];

可以找到如何使用 BWJSONMatcher 的详细示例 here .

关于ios - 使用 JSONModel 库将 jsonarray(具有不同类型)转换为模型数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33407748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com