0

I am trying to iterate trough a JSON array to get both the item key and value.

This is my JSON array:

 {
    "ClientData": [{
        "Name": "Michael"
    }, {
        "Last": "Ortiz"
    }, {
        "Phone": "5555555555"
    }, {
        "email": "[email protected]"
    }],
    "ClientAccess": [{
        "T-Shirt": "YES"
    }, {
        "Meals": "NO"
    }, {
        "VIP": "YES"
    }, {
        "Registration Completed": "Pending"
    }]
}

Now, I am trying to iterate through the "ClientData" array, but for some reason the app is crashing with this exception:

  *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance

This is the code I am using to iterate through the JSON array:

NSDictionary* object = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];

// Client Profile Data

NSDictionary *clientDataDict = [object objectForKey:@"ClientData"];
for (id item in clientDataDict) 
{
    [JSONUserData addObject:[clientDataDict objectForKey:item]];
}

This code was working fine when I didn't have each item on the JSON array placed inside an array. I did this to keep a consecutive order on the array.

Can someone give me any pointers on what the problem is?

Thank you!

2 Answers 2

2

ClientData is an array – represented by the square brackets [] – containing dictionaries with one key/value pair respectively (a quite cumbersome structure).

NSDictionary* object = [NSJSONSerialization JSONObjectWithData:JSONData options:kNilOptions error:nil];

// Client Profile Data

NSArray *clientDataArray = [object objectForKey:@"ClientData"];
for (NSDictionary *dict in clientDataArray) {
   for (NSString *key in dict) {
      [JSONUserData addObject:[dict objectForKey:key]];
   }
}
Sign up to request clarification or add additional context in comments.

1 Comment

If at all possible, talk to the people responsible for generating the JSON and ask them what on earth they are up to. An array of dictionaries, each dictionary with a single key-value pair, that's just ridiculous.
1

According to your JSON strings, it looks like that ClientData pairs with an array and each item in array is a dictionary. Therefore, revised codes will look like:

NSMutableDictionary *mDict = [NSMutableDictionary new];
NSArray *array = [object objectForKey:@"ClientData"];
for (NSDictionary *item in array) {
    [mDict addEntriesFromDictionary:item];
}

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.