Reputation: 580
This is what my JSON
return;
{
"1": {
"name": "Sharon",
"telephone": "48-9929329483"
},
"2": {
"name": "Sage",
"telephone": "48-9560333267"
},
"3": {
"name": "Alex",
"telephone": "48-8467982378"
}
}
I need to save this in a NSDictionary. My workings are as follows;
NSDictionary *contentOfDictionary = [responseString JSONValue];
NSDictionary* studentDictionary = [contentDictionary objectForKey:@"1"];
NSString *nameOfStudent = [studentDictionary objectForKey:@"name"];
NSString *nameOfStudent = [studentDictionary objectForKey:@"telephone"];
NSDictionary* studentDictionary1 = [contentDictionary objectForKey:@"2"];
NSString *nameOfStudent1 = [studentDictionary objectForKey:@"name"];
NSString *nameOfStudent1 = [studentDictionary objectForKey:@"telephone"];
..... etc
So this is what i do to save the attributes to dictionaries
and strings
. But the problem is that i am hard-coding the key value 1,2,3 etc
.. (ex: [contentDictionary objectForKey:@"2"];
)
In reality i don't know how many students will the JSON
file have. There might be 100 or even more. So how can i write this in a way where the code will automatically, read JSON response (all 100 records) and save it to NSDictionary
and vice versa ?
note: I guess i have to use a for loop or something.
Upvotes: 1
Views: 1090
Reputation: 1965
Instead of using NSDictionary
to store responsestring
JSONValue
NSDictionary *contentOfDictionary = [responseString JSONValue];
use NSArray
to store responsestring
JSONValue
NSArray *arr= [responseString JSONValue];
In this way you will get the total count ,each object in the array is a dictionary which can be accessed easily.
Upvotes: 0
Reputation: 1904
Take a look at NSJSONSerialization available since iOS5 (or SBJSON framework). You'll get your JSON parsed and embedded in obj-c objects.
Upvotes: 0
Reputation: 37495
It looks like you have a dictionary in 'contentsOfDictionary' where the keys are "1", "2", ... and the values are dictionaries containing the names/telephone numbers. So you just need to iterate through all the values:
NSMutableArray *studentDictionaries = [[NSMutableArray alloc] init];
for (NSDictionary *studentDictionary in contentOfDictionary.allValues)
{
[studentDictionaries addObject:studentDictionary];
}
Upvotes: 4
Reputation: 6058
If each dictionary entry in your JSON response is uniquely numbered and increasing without gaps, then you could do the following:
NSMutableArray *studentDictionaries = [[NSMutableArray alloc] init];
NSUInteger index = 1;
NSDictionary *studentDictionary;
while (studentDictionary = [contentDictionary objectForKey:[NSString stringWithFormat:@"%d", index++]]) {
[studentDictionaries addObject:studentDictionary];
}
Upvotes: 1