目标C:尝试使用NSArray、NSDictionaries和自定义对象的Dictionary创建JSON字符串



我正试图用许多对象创建一个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];

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

最新更新