1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//
// KWMSearchResult.m
// iCemarose
//
// Created by 陈荣科 on 2016/10/24.
// Copyright © 2016年 kollway. All rights reserved.
//
#import "KWMSearchResult.h"
#import "KWMDataProduct.h"
#import "KWMVariants.h"
@implementation KWMSearchResult
- (instancetype)initWithDictionary:(NSDictionary *)dict
modelClass:(Class)modelClass
error:(NSError **)err {
self = [super initWithDictionary:dict error:err];
NSArray *data = _products.data;
_productList = [NSMutableArray array];
if(data == nil){
return self;
}
for (int i = 0; i < data.count; ++i) {
if(data[i] == nil){
break;
}
KWMDataProduct *dataProduct = [[KWMDataProduct alloc] initWithDictionary:data[i] error:nil];
NSArray *dataArray = data[i][@"variants"];
if(dataArray){
dataProduct.variants = [self buildListData:[KWMVariants class] jsonDictionary:dataArray];
}
[_productList addObject:dataProduct];
}
return self;
}
+(JSONKeyMapper*)keyMapper {
return [JSONKeyMapper mapperFromUnderscoreCaseToCamelCase];
}
- (NSArray *)buildListData:(Class)modelClass jsonDictionary:(NSArray *)dataArray {
if(modelClass == nil){
NSString *reason = [[NSString alloc] initWithFormat:@"class with name:%@ doesn't exists!!", NSStringFromClass(modelClass)];
@throw [[NSException alloc] initWithName:NSInvalidArgumentException reason:reason userInfo:nil];
}
if(! [dataArray isKindOfClass:[NSArray class]]){
NSString *reason = [[NSString alloc] initWithFormat:@"dataArray object is not a NSArray instance"];
@throw [[NSException alloc] initWithName:NSInvalidArgumentException reason:reason userInfo:nil];
}
NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
for(NSDictionary *itemJson in dataArray){
NSError *error;
id result = [[modelClass alloc] initWithDictionary:itemJson error:&error];
if(error){
NSLog(@"buildListData error: %@", [error localizedDescription]);
}else{
[mutableArray addObject:result];
}
}
return [[NSArray alloc] initWithArray:mutableArray];
}
@end