我有自定义类对象,其中包含用户对象:
@interface Order : NSObject
@property (nonatomic, retain) NSString *OrderId;
@property (nonatomic, retain) NSString *Title;
@property (nonatomic, retain) NSString *Weight;
@property (nonatomic, retain) User *User
- (NSMutableDictionary *)toNSDictionary;
...
- (NSMutableDictionary *)toNSDictionary
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:self.OrderId forKey:@"OrderId"];
[dictionary setValue:self.Title forKey:@"Title"];
[dictionary setValue:self.Weight forKey:@"Weight"];
return dictionary;
}
在toNSDictinary
函数中我没有映射User
对象。
在这种情况下,将对象转换为 nsdictionary
的好方法是什么?
最佳答案
修改你的toNSDictionary
方法:
- (NSMutableDictionary *)toNSDictionary
{
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setValue:self.OrderId forKey:@"OrderId"];
[dictionary setValue:self.Title forKey:@"Title"];
[dictionary setValue:self.Weight forKey:@"Weight"];
NSMutableDictionary *userDictionary = [NSMutableDictionary dictionary];
[userDictionary setValue:self.User.someProperty1 forKey:@"someProperty1"];
[userDictionary setValue:self.User.someProperty2 forKey:@"someProperty2"];
[dictionary setValue:userDictionary forKey:@"User"];
return dictionary;
}
关于ios - 当对象具有内部对象时如何将对象转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21330828/