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

标签 ios objective-c json nsmutabledictionary nsjsonserialization

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

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

相关文章:

ios - 按字符串日期和 bool IOS 对对象数组进行排序

objective-c - 在 Xcode 中删除断点

ios - 在 View Controller 之间传递数据

ios - 如何分配 skpayment 应用程序用户名

PHP json_encode array(3) 返回 false

ios - 找不到 RKJSONParserJSONKit.h

ios - Ionic iOS 13.2 Bug,应用程序崩溃 - Kill() 返回意外错误

ios - Swift 相当于 "[[transferManager download:downloadRequest] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task)"

json - 使用 GO 返回一个结构数组作为 Json 响应

json - Spring Boot json 在没有默认构造函数的情况下建模