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

Posted

技术标签:

【中文标题】当对象具有内部对象时如何将对象转换为 JSON【英文标题】:How to convert object to JSON when object have inner object 【发布时间】:2014-01-24 10:55:45 【问题描述】:

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

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

【问题讨论】:

把你的问题说清楚 【参考方案1】:

修改你的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;

【讨论】:

【参考方案2】:
- (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: ]

【讨论】:

以上是关于当对象具有内部对象时如何将对象转换为 JSON的主要内容,如果未能解决你的问题,请参考以下文章

如何将 MongooseMap 转换为 JSON 对象以将其从 Node js 发送到 React?

将每个具有一个对象的 JSON 对象数组转换为 JSON 对象数组 [关闭]

将java对象转换为具有不同对象名称的json

如何在将jsonObject转换为模型对象时检测缺失的字段

如何将具有元素数组的每个对象的对象列表转换为具有子元素作为属性的对象数组

将 JSON 对象传递给 MVC 控制器时 string.empty 转换为 null