0

I call an URL that returns me JSON (I use JSONKit). I convert it to a NSString that is this way:

[{"name":"aaaaaa","id":41},{"name":"as","id":23},...

And so on. I want to fill an UIPickerView with only the "name" part of the JSON. But, when the user selects a name, i need the "id" parameter, so i've thought to fill a NSDictionary with the JSON (setValue:id for key:name), so i can get the value picked by the user, and get the id from the dictionary. how could I fill an array with only the "name" of the JSON?

Im a bit lost with the JSONKit library, any guidance? Thank you.

Fustigador
  • 6,339
  • 12
  • 59
  • 115

1 Answers1

1

First of all I don't think that its a good idea to have name as key in a dictionary, since you can have many identical names. I would go for id as key.

Now, what you could do is:

NSString *myJson; //Suppose that this is the json you have fetched from the url
id jsonObject = [myJson objectFromJSONString];
// Now you have an array of dictionaries 
// each one having 2 key/value pairs (name/id)

NSArray *names = [jsonObject valueForKeyPath:@"name"];
NSArray *ids = [jsonObject valueForKeyPath:@"id"];

// Now you have two parallel arrays with names / ids

Or you could just iterate your json object and handle the data yourself:

for (id obj in jsonObject)
{
  NSString *name = [obj valueForKey:@"name"];
  NSNumber *id = [obj valueForKey:@"id"];
  // Do whatever you like with these
}
Alladinian
  • 34,483
  • 6
  • 89
  • 91
  • Are these arrays truly parallel? I mean, if the 15th element in the jsonstring has "name:myself id=76", the [namearray objectanIndex:15] will return "myself" and [idsarray objectAtIndex:15] will return 76? – Fustigador Jul 02 '12 at 09:33
  • Ok Alladinian :) Thank you very much. – Fustigador Jul 02 '12 at 09:36