如何将类对象转换为NSDictionary?

时间:2016-07-20 08:06:22

标签: ios objective-c nsdictionary data-conversion

我必须转换NSDictionary中的类对象

我有以下课程

test.txt

mealItems包含FoodItems,它是一个类对象。

FoodItems有一个变量营养成分,实际上是一个Class对象。

是否有一种将FoodMeal类转换为NSDictionary的有效方法。

提前致谢。

3 个答案:

答案 0 :(得分:2)

你可以使用jsonmodel

请参阅此链接https://github.com/jsonmodel/jsonmodel

例如:

在xcode项目中下载jsonmodel导入

然后

@interface FoodMeal : JSONModel

@property (nonatomic,strong) NSString *mealType;
@property (nonatomic,strong) NSString *mealName;
@property (nonatomic,strong) NSArray *mealItems;
@property (nonatomic,strong) NSDate *mealDate;

@end

创建jsonmodel的类子类。 jsonmodel超类是NSObject。

比你想把你的类对象转换为Dictionary然后像这样使用它

FoodMeal *ob = [FoodMeal alloc]init];

NSDictionary *dictob = [ob toDictionary];

toDictionary是JSONModel中返回NSDictionary;

的方法

答案 1 :(得分:1)

只需在 FoodMeal

中编写一个方法即可
- (NSDictionary *)dictionaryRepresentation
{
    NSMutableDictionary *mutableDict = [NSMutableDictionary dictionary];

    [mutableDict setValue:self.mealType forKey:@"KeyForMealType"];
    [mutableDict setValue:self.mealName forKey:@"KeyForMealName"];
    [mutableDict setValue:self.mealItems forKey:@"KeyForMealItem"];
    [mutableDict setValue:self.mealDate forKey:@"KeyForMealDate"];

    return [NSDictionary dictionaryWithDictionary:mutableDict];
}

之后您可以将此方法用作

FoodMeal *food = [FoodMeal alloc] init];
 food.mealType = @"ABC";
 food.mealName = @"DEF"
 food.mealItems = @[@"Item 1", @"Item 2",@"Item 3",@"Item 4"];
 food.mealDate = [NSDate date];

 [food dictionaryRepresentation];

答案 2 :(得分:0)

尝试一下:

#import <objc/runtime.h>


//Add this utility method in your class.
+ (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])];
        [dict setObject:[obj valueForKey:key] ? [obj valueForKey:key] : @"" forKey:key];
    }

    free(properties);

    return [NSDictionary dictionaryWithDictionary:dict];
}