I've been having trouble finding out how to convert a JSON array into an NSArray.
I have a php script that creates an array that is converted into JSON which is then sent and stored into an NSString that looks like:
My problem is that I need to make that into an NSArray of ints. How would one do that?
preguntado el 01 de febrero de 12 a las 22:02
You should look at the documentation of the NSJSONSerialización clase.
You can hand it the
NSData received from a remote call that is a string in JSON format and receive the array or dictionary it contains.
NSObject *o =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error]; // other useful "options": // 0 // NSJSONReadingMutableLeaves // NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers
you should then check that
o is of the type you expect for sanity purposes
If I wanted to quickly break that into an array I would do it like this:
NSString * jstring = @"[1,2,3,4]"; //your json string jstring = [jstring stringByReplacingOccurrencesOfString:@"[" withString:@""]; jstring = [jstring stringByReplacingOccurrencesOfString:@"]" withString:@""]; NSArray * intArray = [string componentsSeparatedByString:@","]; //you could create your int from the array like this int x = [[intArray objectAtIndex:0]intValue];
Import the SBJson in your project (drag and drop it)
Then where you receive the JSON response from the php file
NSArray *array = [responseString JSONValue];