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: ]