Pregunta

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.

¿Fue útil?

Solución

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
}
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top