-5

I have created an API and the results are given out in json in the following format:

{"response":"ok","data":[{"file_name":"sample file name one","server_url":"someurl","file_thumb":"images\/7ibysd4f8wiy_t.jpg"},{"file_name":"sample file name two","server_url":"someurl","file_thumb":"images\/jm3t6aat8uhq_t.jpg"}]}

till now I was using the following function:

- (NSArray*) jsonToArray:(NSString *)responseData{

    NSData* data = [responseData dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *values = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];  // if you are expecting  the JSON string to be in form of array else use NSDictionary instead

    return values;

}

and then I would get the array like:

data_array = [self jsonToArray:data_js];
[data_array valueForKey:@"data"]

but how I be able to loop through the data array? is that possible with the current method?

bdesham
  • 15,430
  • 13
  • 79
  • 123
Ahoura Ghotbi
  • 2,866
  • 12
  • 36
  • 65
  • 2
    "how to decode json data to an array in xcode" - you can't, Xcode is not a JSON parser. –  Aug 09 '13 at 18:21
  • so what data can xcode parse easily? what data should I return in my API to be able to read it easily on xcode? – Ahoura Ghotbi Aug 09 '13 at 18:23
  • At best, Xcode can parse its own data formats (for example, Xcode project files). I bet you don't want to parse JSON using Xcode, but using **your application.** Those are two different things, and if this is indeed the case, then your question has **nothing** to do with Xcode whatsoever. –  Aug 09 '13 at 18:24
  • my bad, I meant objective-c not xcode in particular... – Ahoura Ghotbi Aug 09 '13 at 18:26
  • 1
    Then have a look at the answer I've posted a link to, you are most probably looking for Objective-C fast enumeration: `for (id element in array) { ... }` –  Aug 09 '13 at 18:28
  • Based on the data shown, each element in the array is probably an NSDictionary. Iterate through the array and work with each element as a dictionary. – Aaron Bratcher Sep 29 '13 at 12:20

1 Answers1

0

Try using the new enumerateObjectsUsingBlock API on NSDictionary and NSArray. You can call that on your variable returned by NSJSONSerialization

It's super simple and gives you a little bit cleaner code than fast enumeration.

http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSArray_Class/NSArray.html#//apple_ref/occ/instm/NSArray/enumerateObjectsUsingBlock:

Jeremy Massel
  • 2,257
  • 18
  • 22