1

我有一个包含在其中的用户对象的自定义类对象:如何对象转换为JSON对象时,有内部对象

@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的好方法是什么?

+0

与乌尔问题明确设置字典密钥尝试 – Chandru

回答

2

修改您的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; 
} 
0
- (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 setObject:userDictionary forKey:@"User"]; 

return dictionary; 
} 

同时使用

[dictionary setObject: forKey: ]