Using an API (which I am writing) I need to return a fairly simple array from a server running PHP using JSON for use in Objective-C.
On the phone, the code will be added to an array of the following form:
NSArray *carPics =@[@[@"ford",@"ford.png"],@[@"bmw",@"bmw.png"];
I can return the above in JSON as a string by escaping all the special characters--a bit tedious but possible, or replacing the special characters with magic strings like ***. and then make the string as an array using :
NSArray *arr = [str componentsSeparatedByString:@"***"];
On the other hand, I could create an array in PHP and return the array to the phone which would then have to convert the array to Objective-C.
$carpics = array(
array(
"ford" => "ford.png",
"bmw" => "bmw.png",
);
The downside of this is it would involve more conversions.
Is either approach better or are they six of one, half a dozen of the other?
Edit
Currently the JSON sent by server looks like this:
{"carpics":{"ford":"ford.png","bmw":"bmw.png"}}
I am trying to decode it on phone using:
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:jsonFeed
options:kNilOptions
error:&error];
NSMutableArray *carPics = [[json objectForKey:@"carpics"]mutableCopy];
NSArray *myArray = carPics;
This works fine. I have verified that json is a dictionary. Unfortunately, I have also verified using kindOfClass that carpics or myArray is not an array as I want but a dictionary too.
If I try to grab the first element of myArray using:
NSArray *object = myArray[i];
I get an error:
[__NSDictionaryM objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x174449420'
I really want an array as I wish to go through each element of the array in order one at a time.
What do I need to do for my JSON to be a proper array of arrays. I can either change the JSON coming from the server or process the JSON differently on the phone.
Here is the PHP code that creates the JSON:
header("Content-Type: application/json");
$ret = array("ford"=>"ford.png","bmw"=>"bmw.png");
echo json_encode(array('carpics'=>$ret));