繁体   English   中英

当对象具有内部对象时如何将对象转换为JSON

[英]How to convert object to JSON when object have inner object

我有自定义类对象,其中包含用户对象:

@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;
}
- (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: ]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM