【问题标题】:Objective C: Trying to create a JSON String with a Dictionary of NSArrays, NSDictionaries and custom objects目标 C:尝试使用 NSArrays、NSDictionaries 和自定义对象的字典创建 JSON 字符串
【发布时间】:2013-07-19 19:03:21
【问题描述】:

我正在尝试从多个对象中创建一个 JSON 字符串。基本上我这样做是为了将数据库的一部分发送回服务器,以便它可以更新自上次连接以来所做的事情。我希望能够将对象字典转换为 NSData 或 JSON 字符串并将其发送出去,但是当我尝试调用 NSJSONSerialization dataWithJSONObject 时失败了。任何想法如何最好地解决这个问题?我需要分别做这些对象中的每一个吗?即使那样,我将如何处理自定义对象数组。

SchedModel *sched = [self retrieveSchedData]; //custom object
NSArray *event = [self retrieveEvents];  //Array of custom objects
NSDictionary *info = [self retrieveInfo]; //plain old NSDictionary

NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

// Load all objects into a dictionary
[dict setObject: sched forKey:@"sched"];
[dict setObject: event forKey:@"event"];
[dict setObject: info forKey:@"info"];

NSError * error = nil;

//Now create the NSData for this object (THIS FAILS)
NSData * jsonData = [NSJSONSerialization dataWithJSONObject: dict options:NSJSONReadingMutableContainers error:&error];
NSString *JSONString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding];

【问题讨论】:

    标签: ios json nsjsonserialization


    【解决方案1】:

    您不能序列化自定义对象。您必须在序列化之前将sched 转换为NSDictionary

    【讨论】:

    • 是否有一种通用的方法可以将 sched 转换为字典,或者我需要在我的所有自定义对象中创建一个 toDictionary 方法。
    • 这将是主要方式,因为只有您知道应该序列化哪些属性/iVar。但是,您可以使用 Obj-C 运行时检查所有属性并对其进行编码。
    • 你可以看看 Mantle 做类似的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-07
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多