问题
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:
[1,2,3,4]
My problem is that I need to make that into an NSArray of ints. How would one do that?
Thanks!
回答1:
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];
回答2:
You should look at the documentation of the NSJSONSerialization class.
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
回答3:
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];
来源:https://stackoverflow.com/questions/9104632/how-to-convert-a-json-array-into-an-nsarray