将嵌套的Model类对象作为JSON api参数传递

时间:2018-05-28 09:56:30

标签: ios objective-c

我有Model Class,constist各种属性,有些属性也包含另一个模型类的对象。我的问题是我想直接将Model类对象作为JSON api参数传递。

请建议我。

实施例。

#import "locationModel.h"
interface userModel:NSObject

@property (nonatomic,retain) NSString *uName;

@property (nonatomic,retain) locationModel *mLocation;
// locationModel consist two Properties Lat Lng

@end

我想将objUserModel作为参数传递给json api。 请建议我将objUserModel作为jsonapiparameters传递。

非常感谢

1 个答案:

答案 0 :(得分:1)

您可以创建一个ModelObject类,并将所有模型类更改为此类的子类。然后将dictionaryWithPropertiesOfObject:的实现更改为以下内容:

- (NSDictionary *)dictionaryWithPropertiesOfObject:(id)obj {
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    unsigned count;
    objc_property_t *properties = class_copyPropertyList([obj class], &count);
    for (int i = 0; i < count; i++) {
        NSString *key = [NSString stringWithUTF8String:property_getName(properties[i])];
        if([obj valueForKey:key]!=nil){
            id targetObject = [obj valueForKey:key];
            if ([targetObject isKindOfClass:[ModelObject class]]){
                [dict setObject:[self dictionaryWithPropertiesOfObject: targetObject]  forKey:key];
            }
            else if ([targetObject isKindOfClass:[NSArray class]]){
                [dict setObject:[self arrayWithDictionariesForObjectsInArray: (NSArray *)targetObject] forKey:key];
            }
            else {
                [dict setObject:targetObject forKey:key];
            }
        }
    }
    free(properties);
    return [NSDictionary dictionaryWithDictionary:dict];
}

- (NSArray *) arrayWithDictionariesForObjectsInArray: (NSArray *) array {
    NSMutableArray *mutableArray = [[NSMutableArray alloc] init];
    for (id object in array){
        [mutableArray addObject:[self dictionaryWithPropertiesOfObject:object]];
    }
    return [NSArray arrayWithArray:mutableArray]; 
}

因此,ModelObject的所有实例都会在字典中插入字典表示。