JSON to NSMutableArray iOS

601 views Asked by At

As a response to a request I get JSON:

{
    "letters": {
        "A": 0,
        "B": 1,
        "C": 2,
        "D": 3,
        "E": 4,
        ...
    }
}

That's my code to acquire this JSON:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

NSLog(@"%@", responseObject);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // Handle error
}];

I want to fill array with keys (not values) like this:

array[0] = "A"

array[1] = "B" ...?

4

There are 4 answers

4
Ruchish Shah On
NSMutableArray *parts = [NSMutableArray new];

NSDictionary *allletters = [responseObject objectForKey:@"letters"];

for (NSString *key in [allletters allKeys])
{

    NSString *value = [allletters objectForKey: key];

    [parts insertObject:key atIndex:[val intValue]];
}
0
agy On

I haven't tested the code. But it should be something similar to this:

NSDictionary *responseDictionary = (NSDictionary*)responseObject;

NSDictionary *letters = [responseDictionary objectForKey:"letters"];
NSMutableArray *lettersArray = [[NSMutableArray alloc]init];


if ( letters ){

for (NSInteger i = 0; i < letters; ++i)
{
  [lettersArray addObject:[NSNull null]];
}
[letters enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                          usingBlock:^(id key, id object, BOOL *stop)     {
   [lettersArray replaceObjectAtIndex:[key integerValue] withObject:object]
}]

}
0
Mahmoud Adam On

try the following code

NSDictionary *letters = [responseObject objectForKey:"letters"];
NSArray *lettersArray = [letters allKeys];
0
vikingosegundo On

As you are already using the JSON response serializer, responseObject should be a dictionary.

To get all keys of the sub dictionary letters, do

NSArray *letters = [reponseObject[@"letters"] allKeys];

No need for a mutable array here. But if you want it mutable , do

NSMutableArray *letters = [[reponseObject[@"letters"] allKeys] mutableCopy];