0

I am trying to create a JSON String out of a number of objects. Basically I am doing this to send up a portion of the database back to the server so it can update what has been done since it was last connected. I was hoping to be able to convert the dictionary of objects into an NSData or a JSON String and send that up, but I am failing when I attempt to call NSJSONSerialization dataWithJSONObject. Any thoughts how best to approach this? Do I need to do each of these objects separately? Even then, how would I handle the array of custom objects.

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];
DaveB
  • 181
  • 3
  • 11

1 Answers1

0

You can't serialize custom objects. You have to convert sched to a NSDictionary before serialization.

Marcelo
  • 9,916
  • 3
  • 43
  • 52
  • Is there a generic way to convert sched to a dictionary or would I need to create a toDictionary method in all of my custom objects. – DaveB Jul 20 '13 at 02:59
  • That'd be the main way, as only you know which properties/iVars should be serialized. However, you can use Obj-C runtime to inspect all properties and encode them. – Marcelo Jul 20 '13 at 03:02
  • You can look at [Mantle](https://github.com/github/Mantle) that does something like that. – Marcelo Jul 20 '13 at 03:05