I am trying to send an array of custom objects to a server using JSON.
I have tried two approaches. One I stringify the array of objects and send it.
NSArray <Offers *> *offers = [self getOffers];
NSString *offersString = [offers componentsJoinedByString:@","];
This gets it to the server but on the server end, I end up with an incredibly complicated string that makes reconverting in to structured data on the server which uses PHP a challenge. Also since something could go awry with the string in transmission, it would seem to be a fragile approach.
The second approach is to serialize the array of objects into a JSONData object on the phone and send it. The problem with this is that I also want to send some other data such as an authentication string/token And I don't know how to assemble a JSONData object that contains the authentication string on the one hand and the JSONData containing the array of objects on the other.
In fact my code is crashing when I try to create a dictionary that contains an NSData object.
NSArray <Offers *> *offers = [self getOffers];
NSError *error;
NSMutableArray<NSDictionary*> *jsonOffers = [NSMutableArray array];
for (Offers* offer in offers) {
[jsonOffers addObject:[offer toJSON]];
}
NSData * OffersJSONData = [NSJSONSerialization dataWithJSONObject:jsonOffers
options:kNilOptions
error:&error];
NSMutableDictionary *dict = [[NSMutableDictionary alloc]initWithCapacity:50];
[dict setObject:authtoken forKey:@"token"];
[dict setObject:OffersJSONData forKey: @"offersobject"];
//FOLLOWING LINE CRASHES
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithDictionary:dict];
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonDictionary
options:0 error:&error];
[self postToServer:data];
Can anyone suggest a way to create a JSON object that can contain both a string and an NSData structure at the same time?
Thanks in advance for any suggestions.