2

次の JSON blob があるとします。

[
  {
    type: "audio",
    title: "Audio example title",
  },
  {
    type: "video",
    title: "Video example title",
  },
  {
    type: "audio",
    title: "Another audio example title",
  },
]

および 2 つの JSONModel モデル クラス (AudioModel、VideoModel)。JSONModel がtypeJSON をモデルにマップするときに、プロパティに基づいてこれらのモデル クラスのいずれかを自動的に作成することは可能ですか?

4

2 に答える 2

0

これに関して、JSONModel の貢献者の間でかなりの議論が行われました。結論としては、独自のクラス クラスタを実装することが最善の選択肢であると思われます。

これを行う方法の例 - GitHubの問題に関する私のコメントからコピー:

+ (Class)subclassForType:(NSInteger)pipeType
{
    switch (pipeType)
    {
        case 1: return MyClassOne.class;
        case 2: return MyClassTwo.class;
    }

    return nil;
}

// JSONModel calls this
- (instancetype)initWithDictionary:(NSDictionary *)dict error:(NSError **)error
{
    if ([self isExclusiveSubclass])
        return [super initWithDictionary:dict error:error];

    self = nil;

    NSInteger type = [dict[@"type"] integerValue];
    Class class = [MyClass subclassForType:type];

    return [[class alloc] initWithDictionary:dict error:error];
}

// returns true if class is a subclass of MyClass (false if class is MyClass)
- (BOOL)isExclusiveSubclass
{
    if (![self isKindOfClass:MyClass.class])
        return false;

    if ([self isMemberOfClass:MyClass.class])
        return false;

    return true;
}
于 2016-01-12T12:15:23.167 に答える
0

ループを使用しfor..inて type プロパティをチェックし、以下のような型に基づいて Model オブジェクトを作成することが可能です

NSMutableArray *audioModelArray = [NSMutableArray alloc] init];
NSMutableArray *videoModelArray = [NSMutableArray alloc] init];

    for(NSdictionary *jsonDict in jsonArray) {
        if(jsonDict[@"type"] isEqualToString:@"audio") {
             AudioModel *audio  = [AudioModel alloc]initWithTitle:jsonDict[@"title"]]; 
            [audioModelArray addObject: audio];
        } else {
          VideoModel *audio  = [VideoModel alloc]  initWithTitle:jsonDict[@"title"]];
         [videoModelArray addObject: audio];
        }
    }

次に、オブジェクトを繰り返し処理してaudioModelArrayvideoModelArrayaudoModel および videoModel オブジェクトとそれらのプロパティにアクセスできます。

于 2015-07-30T09:54:36.267 に答える