2

I have this json array which I have outlined below. I want to know how I could get all the strings under the "name" key only and place in a certain array to be sorted alphabetically by name and later split into further arrays in accordance to the first letter in the names. Any guide to carrying this out will be much appreciated, thanks. I am using the json kit via github and also NSJSONserialization.

 {
   "proj_name": "Ant",
   "id": 
      [
          {
             "name": "David"
          },
          {
             "name": "Aaron"
          }
      ]
 },
 {
    "proj_name": "Dax",
    "id": 
         [
           {
             "name": "Adrian"
           },
           {
             "name": "Dan"
           }
         ]
  }
3
  • 1
    Don't use JSON. Parse into arrays and dictionaries and deal with those. Forget it was ever JSON. Commented Jan 30, 2013 at 13:22
  • @HotLicks Why do you suggest that ? Would like to further understand Commented Jan 30, 2013 at 16:02
  • I'm saying, don't focus on the fact that it was JSON. Convert it to the Objective-C objects and figure out how to access those. Commented Jan 30, 2013 at 17:54

3 Answers 3

3

Here is sample that selects just names and sort them alphabetically. Replace responseData with your data object.

NSMutableArray *names = [[NSMutableArray alloc] init];

NSError* error;
NSArray* json = [NSJSONSerialization 
    JSONObjectWithData:responseData
    options:kNilOptions 
    error:&error];

for (NSDictionary *proj in json) {
    NSArray *ids = [proj objectForKey: @"id"];

    for (NSDictionary *name in ids)
    {
        [names addObject: [name objectForKey: @"name"];
    }
}

NSArray *sortedNames = [names sortedArrayUsingSelector: @selector(localizedCaseInsensitiveCompare:)];
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you @Madman :) I get a warning "Incompatible pointer types asigning to 'NSMutableArray *__strong' from NSArray", what seems to be the issue, i tried changing the NSArrays to NSMutableArrays also but that din't change anything
sweet, thanks a lot!! that work I am able to see the correct outputs showing all the names in alphabetical other, I decided to display the values in a UIPickerView. It displays the first three names but not the forth
Maybe you forgot to implement (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component ?
I definitely did that using return [self.sortedNames count];
3

Go to http://json.bloople.net/ in this link you can see the structure of your JSON response.

from the above response i can see the response as follow:

Project name: Dax

id : 0 name : Adrian

  1  name : Dan

So you can use the NSjsonserialization class from Apple. No need to use JSON kit.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"Your URL"]]];
  NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];

    NSLog(@"url=%@",request);

id jsonObject = [NSJSONSerialization JSONObjectWithData:response options:NSJSONReadingAllowFragments error:nil];

if ([jsonObject respondsToSelector:@selector(objectForKey:)])

    {
    Nsstring *projectname=[jsonObject objectForKey:@"proj_name"];
    NSArray *name_array=[jsonObject objectForKey:@"id"];

     NSLog(@"projectname=%@",projectname);
     NSLog(@"name_array=%@",name_array);
    }

4 Comments

Ahh I see Thank you Siba, I will give it a go and get back to you
Why would you do synchronous request and not asynchronous?
it can be done Asynchronous Also. Just have to add the Delegate methods of NSURLconnection.
@Siba If I wanted to go a step further and display the strings contained in the the "names_array" in a UIPickerView how can I accomplish that? I am using the methods: - (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component // - (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
0

Assuming you've successfully parsed the JSON into an NSArray, you can simplify things pretty dramatically:

NSArray *names = [parsedArray valueForKeyPath:@"@distinctUnionOfArrays.id.name"];

The names array should now contain all of the names flattened into a single array. To sort them, you could then do:

NSArray *sortedNames = [names sortedArrayUsingDescriptors:@[[NSSortDescriptor 
                                      sortDescriptorWithKey:@"description" ascending:YES]]];

Or all at once:

  NSArray *sortedNames = [[parsedArray valueForKeyPath:@"@distinctUnionOfArrays.id.name"]
                          sortedArrayUsingDescriptors:@[[NSSortDescriptor 
                                                 sortDescriptorWithKey:@"description"
                                                             ascending:YES]]];

The sortedNames array would now contain:

<__NSArrayI 0x713ac20>(
Aaron,
Adrian,
Dan,
David
)

Comments

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.