How to convert a JSON array into an NSArray

萝らか妹 提交于 2019-12-08 10:40:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!