目标C:尝试使用NSArrays,NSDictionaries和自定义对象的字典创建JSON字符串

时间:2013-07-19 19:03:21

标签: ios json nsjsonserialization

我正在尝试从许多对象中创建一个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];

1 个答案:

答案 0 :(得分:0)

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