gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 10:48:46 24 4
gpt4 key购买 nike

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

@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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com