Cómo convertir una matriz JSON en una NSArray

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

Does your app process JSON or a string? -

There is no such thing as an NSArray of ints. NSArrays, NSDictionarys and NSSets may only contain ObjC-style objects, so what you would get using any of the JSON-Frameworks out there (i prefer JSONKit) will be an NSArray of NSNumbers. -

3 Respuestas

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 

// other useful "options":
// 0 
// NSJSONReadingMutableLeaves
// NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers

you should then check that o is of the type you expect for sanity purposes

Respondido 02 Feb 12, 03:02

This should be the way people go with JSON in iOS as more people install iOS5 on their devices. - colincameron

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];

Respondido 02 Feb 12, 22:02

yea ... no, he would not have an int-array, he would have an array with NSStrings. - Dios del agua

yeah sorry, you would have to pull the strings as intValue - Louie

Thanks! This worked great. But how could I pull the strings as intValues? - user1072264

Import the SBJson in your project (drag and drop it)

#import "SBJson.h"

Then where you receive the JSON response from the php file

NSArray *array = [responseString JSONValue];

Respondido 02 Feb 12, 03:02

This works for decoding the JSON in the php but when I send it to the NSString all that appears is Array Also, I was thinking I would have to edit my .m file in the iOS app, not the php. - user1072264

aha. My bad. There is a great json library in Objective-c: github.com/stig/json-framework - Andreas Helgegren

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.