0

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!

2
  • Does your app process JSON or a string? Commented Feb 1, 2012 at 23:18
  • 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. Commented Feb 2, 2012 at 1:03

3 Answers 3

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

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

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

3 Comments

yea ... no, he would not have an int-array, he would have an array with NSStrings.
yeah sorry, you would have to pull the strings as intValue
Thanks! This worked great. But how could I pull the strings as intValues?
0

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

2 Comments

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.
aha. My bad. There is a great json library in Objective-c: github.com/stig/json-framework

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.