【问题标题】:How to convert object to JSON when object have inner object当对象具有内部对象时如何将对象转换为 JSON
【发布时间】: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 的好方法是什么?

【问题讨论】:

  • 把你的问题说清楚

标签: ios objective-c json nsmutabledictionary nsjsonserialization


【解决方案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: ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2020-10-13
      • 2016-04-24
      • 1970-01-01
      • 1970-01-01
      • 2023-02-15
      相关资源
      最近更新 更多