Passing returned data into array,iOS - iphone

I m using JSON and while parsing, i m getting the returned value as
> [{"id":"2","name":"a"}, {"id":"3","name":"b"},
> {"id":"104","name":"c"}, {"id":"4","name":"d"}]
I want to have the 'name' in some array, so that i can show the names in picker view.
from array to pickerview, i can perform,but i m getting problem in retrieving the values of name and put into an array.

jsonArray = [{"id":"2","name":"a"}, {"id":"3","name":"b"},
{"id":"104","name":"c"}, {"id":"4","name":"d"}]
NSMutableArray *nameArray = [[NSMutableArray alloc] initWithCapacity:0];
for(NSMutableDictionary *dict in jsonArray){
NSString *str = [dict objectForKey:#"name"];
if(str){
[nameArray addObject:str];
}
}
This your name array... hope this will help you

You'll need some kind of JSON parser library, which makes a discrete data collection type (for example, an NSDictionary or NSArray) out of the JSON string. I've written one library which I prefer:
https://github.com/H2CO3/CarbonateJSON/
There are also a lot of older and probably better solutions; consider JSONKit:
https://github.com/johnezang/JSONKit
And SBJSON (a. k. a. JSON framework):
https://github.com/stig/json-framework
Hope this helps.

jsonArray = [{"id":"2","name":"a"}, {"id":"3","name":"b"},
{"id":"104","name":"c"}, {"id":"4","name":"d"}]
NSMutableArray *nameArray = [[NSMutableArray alloc] init];
for(int i=0;i<jsonarray.count;i++){
if([[jsonArray objeactAtIndex:i] objectForKey:#"name"])
{
NSString *str =[[jsonArray objeactAtIndex:i]
objectForKey:#"name"];
[nameArray addObject:str];
}
}
Its Working Properly.

Related

How to parse the JSON response?

I am working on a project where the facebook's friend list have to de displayed. I did all necessary coding to get the reponse , but the reponse is like the following
{"data":[{"name":"Ramprasad Santhanam","id":"586416887"},{"name":"Karthik Bhupathy","id":"596843887"},{"name":"Anyembe Chris","id":"647842280"},{"name":"Giri Prasath","id":"647904394"},{"name":"Sadeeshkumar Sengottaiyan","id":"648524395"},{"name":"Thirunavukkarasu Sadaiyappan","id":"648549825"},{"name":"Jeethendra Kumar","id":"650004234"},{"name":"Chandra Sekhar","id":"652259595"}
Can anyone please tell me how to save name and id in two different arrays.
Any help will be appreciated.
you can see below how html response parse . there i am getting facebook friends.
- (void)fbGraphCallback:(id)sender
{
if ( (fbGraph.accessToken == nil) || ([fbGraph.accessToken length] == 0) )
{
//restart the authentication process.....
[fbGraph authenticateUserWithCallbackObject:self andSelector:#selector(fbGraphCallback:)
andExtendedPermissions:#"user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins"];
}
else
{
NSLog(#"------------>CONGRATULATIONS<------------, You're logged into Facebook... Your oAuth token is: %#", fbGraph.accessToken);
FbGraphResponse *fb_graph_response = [fbGraph doGraphGet:#"me/friends" withGetVars:nil];// me/feed
//parse our json
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary * facebook_response = [parser objectWithString:fb_graph_response.htmlResponse error:nil];
//init array
NSMutableArray * feed = (NSMutableArray *) [facebook_response objectForKey:#"data"];
// NSMutableArray *recentFriends = [[NSMutableArray alloc] init];
arr=[[NSMutableArray alloc]init];
//adding values to array
for (NSDictionary *d in feed)
{
[arr addObject:d];
}
//NSLog(#"array is %# ",arr);
[fbSpinner stopAnimating];
[fbSpinner removeFromSuperview];
[myTableView reloadData];
}
}
This is json response you are getting. So you need a JSON parser to convert this string into Objective-C objects. In iOS App, you can use a library like the json-framework. This library will allow you to easily parse JSON and generate json from dictionaries / arrays (that's really all JSON is composed of).
From SBJson docs: After JSON parsing you will get this conversion
JSON is mapped to Objective-C types in the following way:
null -> NSNull
string -> NSString
array -> NSMutableArray
object -> NSMutableDictionary
true -> NSNumber's -numberWithBool:YES
false -> NSNumber's -numberWithBool:NO
integer up to 19 digits -> NSNumber's -numberWithLongLong:
all other numbers -> NSDecimalNumber
That looks like JSON, not HTML. (You probably already knew this, since you tagged the question with json I see.)
I'm not really sure why others are recommending third-party libraries to do this, unless you need to support rather old OS releases. Just use Apple's built-in NSJSONSerialization
class.
This is not HTML. This is JSON. You'll need a JSON parser for this.
A JSON parser would typically make an NSDictionary or NSArray out of the string. With my implementation, you'd do something like this:
NSMutableArray *names = [NSMutableArray array];
NSMutableArray *ids = [NSMutableArray array];
NSDictionary *root = [responseString parseJson];
NSArray *data = [root objectForKey:#"data"];
for (NSDictionary *pair in data)
{
[names addObject:[pair objectForKey:#"name"]];
[ids addObject:[pair objectForKey/#"id"]];
}
Recent versions of iOS contain a new Foundation class, NSJSONSerialization, that will handle any JSON parsing and serialization for you.

iPhone Programming - complex JSON Parsing - UITableView

Hey guys :) I am quite new to stack overflow and iPhone programming. I am trying to parse a complex JSON to display some stuff in the UITableView.
a part of the JSON structure -
{"1":{"1":"Ent1","done":"No"},"2":{"1":"Ent2","done":"No"}}
I am able to parse through the main keys "1" and "2" and able to grab the values corresponding to the key "1" inside {"1":"Ent1","done":"No"}, {"1":"Ent2","done":"No"} store them into a dictionary/ a string with the following code :
for (NSString *key in dict)
{
NSString *answer = [dict objectForKey:#"1"];
NSLog(#"%#", answer);
}
The result is Ent1 and Ent2 because the code iterates over the for loop and checks for the objects with key "1".
The problem is this - I want to store both the values(Ent1 and Ent2) into an array.
I use the following code:
NSMutableArray *array = [[NSMutableArray alloc] initWithObjects: answer, nil];
but it just takes the last index in the dictionary which is Ent2.
Could you please tell me how could I add both the values for key 1 into an array?
Thanks in advance :)
To add to jamapag's answer, you can also use JSON libraries in objective C which do all the work for you like SBJSON or YAJL, or even as part of the more recent versions of the mac/iOS SDKs, NSJSONSerialization.
NSMutableArray *array = [[NSMutableArray alloc] init];
for (NSString *key in dict)
{
NSString *answer = [dict objectForKey:key];
[array addObject:answer];
}

help on sorting NSMutableDictionary strings that are URL images

i want to populate the tablecell with title and imageurl from xml list.
i manage to store the title (NSMutableDictonary *sections )and imageURL (NSMutableDictonary *sectionsImg) into 2 NSMutableDictionary respectively.
/*******This is in viewDidLoad***/
Directory *allDirectory = [appDelegate.directories objectAtIndex:0];
for (allDirectory in appDelegate.directories)
{
NSDictionary *dica = [NSDictionary dictionaryWithObject:allDirectory.dirTitle forKey:#"dirTitle"];
NSDictionary *dico = [NSDictionary dictionaryWithObject:allDirectory.imageURL forKey:#"imageURL"];
[dirName addObject:dica];
[dirImage addObject:dico];
//NSLog(#"dic of items : %#",dirImage);
}
for (allDirectory in appDelegate.directories)
{
//retrieve the first letter from every directory title (dirTitle)
NSString * c = [allDirectory.dirTitle substringToIndex:3];
NSString * m = allDirectory.imageURL;
found = NO;
find = NO;
for (NSString *str in [self.sections allKeys])
{
if ([str isEqualToString:c])
{
found = YES;
}
}
for (NSString *stra in [self.sectionsImg allKeys])
{
if([stra isEqualToString:m])
{
find = YES;
}
}
if (!found)
{
[self.sections setValue:[[NSMutableArray alloc]init] forKey:c ];
[self.sectionsImg setValue:[[NSMutableArray alloc]init] forKey:m];
}
if (!find)
{
[self.sectionsImg setValue:[[NSMutableArray alloc]init] forKey:m];
}
}
for (NSDictionary *directory in dirName)
{
[[self.sections objectForKey:[[directory objectForKey:#"dirTitle"] substringToIndex:3]] addObject:directory];
//NSLog(#"hehehe have : %#",sections);
}
for (NSDictionary *directoryImg in dirImage)
{
//[[self.sectionsImg objectForKey:[[directoryImg objectForKey:#"imageURL"] substringFromIndex:0]] addObject:directoryImg];
[[self.sectionsImg objectForKey:[directoryImg objectForKey:#"imageURL"]] addObject:directoryImg];
//NSLog(#"HOHOHO have : %#",sectionsImg);
}
And on cellForRowAtIndexPath i declare a dictionary
NSDictionary *dictionary = [[self.sections valueForKey:[[[self.sections allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
cell.textLabel.text = [dictionary objectForKey:#"dirTitle"];
but when i tried to declare a dictionary for imageURL
NSDictionary *dictionaryImg = [[self.sectionsImg valueForKey:[[[self.sectionsImg allKeys] sortedArrayUsingSelector:#selector(localizedCaseInsensitiveCompare:)] objectAtIndex:indexPath.section]] objectAtIndex:indexPath.row];
it gives me a error :
Terminating app due to uncaught exception 'NSRangeException', reason: '* -[NSMutableArray objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
any idea why? the logic is supposed to be the same where xml title and url can be retrieve and be displayed. Title is retrievable but imageURL is not. Help is deeply appreciated !
You are trying to sort an array... except for the fact your array isn't an array, but a NSDictionary.
Your code isn't the best at the moment. Your getting the idea of Dictionaries wrong and may be confusing them with arrays, so my best guess is your quite new to programming into objective-c.
You have two lists of things, if I'm not mistaken. The first list is the list of names, and the second list is an image corresponding with that name.
Below I'm going to do two things:
Firstly, I'm giving you two ways on how to fix your problem. It has a sample code included and gives you a small explanation with it. The possibility exist you don't understand parts of what I describe. In that case, you should;
Check out the link I described below the two solutions. It has a tutorial which makes you understand everything about arrays, dictionaries, tables and, as a bonus, XML-parsing.
So, in my opinion, you can do two things:
The first one is using an array of NSDictionaries. You'd be using a code which looks like:
NSMutableDictionary *itemOne = [[NSMutableDictionary alloc] init];
NSMutableDictionary *itemTwo = [[NSMutableDictionary alloc] init];
NSMutableArray *listOfAll = [[NSmutableArray alloc] init];
NSString *itemOneName = [[NSString alloc] initWithFormat:#"This is picture 1"];
NSString *itemTwoName = [[NSString alloc] initWithFormat:#"This is picture 2"];
NSData *imageOneData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://myurl/mypic1.jpg"]];
NSData *imageTwoData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: #"http://myurl/mypic2.jpg"]];
UIImage *itemOneImage = [UIImage imageWithData: imageOneData];
UIImage *itemTwoImage = [UIImage imageWithData: imageTwoData];
[itemOne setObject:itemOneNameString forKey:#"Name"];
[itemOne setObject:itemOneImage forKey:#"Image"];
[itemTwo setObject:itemTwoNameString forKey:#"Name"];
[itemTwo setObject:itemTwoImage forKey:#"Image"];
[listOfAll addObject:itemOne];
[listOfAll addObject:itemTwo];
Anything can be filled using that array. Just use something with a for-loop to iterate through your array.
for (int i = 0; i < [listOfAll count]; i++)
{
NSMutableDictionary *currentItem = [[NSMutableDictionary alloc] initWithDictionary:[listOfAll objectAtIndex:i]];
//Do something with that current item
}
You can also use that index in your tableView. In that case, you have to use your variable section instead of i to get your desired index.
The second one is using two arrays. Imagine you get an image named imageOne with the text imageName. Then you should use:
NSMutableArray *nameList = [[NSMutableArray alloc] init];
[nameList addObject: imageName];
NSMutableArray *imageList = [[NSMutableArray alloc] init];
[imageList addObject: imageOne];
If you want to use a certain item out of those lists, you just have to use the same indexnumber.
For example:
[theTitleLabel setText:[[NSString alloc] initWithFormat:#"%#", [nameList objectAtIndex:x]]];
[theImageView setImage:[imageList objectAtIndex:x]];
Make sure the x's are the same number.
I understand this is all a lot of information, especially if you're new to Objective - C. A tutorial exists which gives you a lot of information about how to use arrays, dictionaries and table views. As a bonus, you get to know a little about XML-parsing.
I suggest you walk through that tutorial and do everything and read everything it says. This should give you a nice start into the world of programming in iPhones.
Good luck!

Creating a Two-Dimensional Array with Concrete Positions

I need to create a custom array:
In php I would define as follows:
$myarray[100][80] = 1;
But I don't know how to do it in objective-c...
I don't need an array [0][0],[0][1],[0][2], ... I only need concrete positions in this array [80][12], [147][444], [46][9823746],...
The content of these positions always will be = 1;
for this you would use a dictionary rather than an array as they are always 0,1,2 keyed so something along the lines of:
NSNumber *one = [NSNumber numberWithInt:1];
NSString *key = #"80,12";
NSDictionary *items = [NSDictionary dictionaryWithObject:one forKey:key];
Then to pull them out again you would use the objectForKey: method.
You cannot put ints directly into arrays or dictionaries that's why it is wrapped in the NSNumber object. To access the int after getting the NSNumber out of the dictionary you would use something like:
NSNumber tempNum = [items objectForKey:key];
int i = tempNum.intValue;
See the docs here for a full explanation of the NSDictionary class. Hope this helps...
I an not a PHP master but I believe in php arrays are not real arrays they are hash tables right?
Anyway, I think you are looking for NSDictionary or NSMutableDictionary class.
That looks more like a bitset than an array.
Allocating so many cells for that seems useless, so maybe you could revert the problem, and store the positions in an array.
Well in objective c we can use NSMutableArray to define 2-D arrays.
See the following code, it might help you
NSMutableArray *row = [[NSMutableArray alloc] initWithObjects:#"1", #"2", nil];
NSMutableArray *col = [[NSMutableArray alloc] init];
[col addObject:row];
NSString *obj = [[col objectAtIndex:0] objectAtIndex:0];
NSLog(#"%#", obj);

Creating Arrays from a plist file in iphone SDK 3.3 and up : objective c

I have run into this issue and have put some major time into finding the answer. I am somewhat new to objective c but not to programming.
Here is my question.
I have a plist file with this structure
root {
A (
{songTitle : contents of song},
{songTitle : contents of song}
),
B (
{songTitle : contents of song}
),
C (
{songTitle : contents of song}
),
... kepps going
}
Sorry if the the plist structure is not correct.
Pretty much I have a root dictionary (that is what it comes with) that contains an array of A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,...Z (alphabet)
Each letter of the alphabet array contains 1 or more dictionaries that have a key, value pair of songTitle (this could be any string) as the key and the song lyrics for the value.
My issue here is I need to create an array of all song titles and have been having a rough time trying to find out how to do this. I own 4 books on object c and none of them go into detail about multidimensional arrays and how to access pieces inside them.
I have created an array with all the letters and have created an array that contains the objects from each letter.
Like I stated before I need to find out how to make an array that contains each song title.
If you can help me that would save me a lot of time.
Thanks,
Wes
I am guessing you are suggesting I change my root from a dictionary to an array?
Maybe it might be better to show my code here.
Also I have attached an updated version of my plist file
Sorry seems I cannot add the image here but you can view it
http://www.wesduff.com/images/forum_images/plist_examp.png
So as you can see I have updated the plist file to show the array of letters that each contain multiple dictionaries. Each dictionary has a songTitle and a songLyrics.
How can I write code to get an array of songTitles.
Here is what I have come up with so far
NSString *path = [[NSBundle mainBundle] pathForResource:#"songs" ofType:#"plist"];
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
//This gives me an array of all the letters in alphabetical order
NSArray *array = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
/**
Now I need to find out how to get an array of all songTitles
**/
I am still working on this and looking through what others have written but have not found anything yet.
As the first answer has suggested, should I change the root to an array or keep it as I have it in this plist image I have attached.
Thanks again,
Wes
Ok so I did some more digging and came up with this from the plist file that was included in this picture
http://www.wesduff.com/images/forum_images/plist_examp.png
- (void)viewDidLoad {
//path for plist file
NSString *path = [[NSBundle mainBundle] pathForResource:#"songList" ofType:#"plist"];
//dictionary created from plist file
NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfFile:path];
//release the path because it is no longer needed
[path release];
//temp array to hold an array of all alphabetical letters
NSArray *array = [[dict allKeys] sortedArrayUsingSelector:#selector(compare:)];
//assign array to allLetters array
self.allLetters = array;
//Create two mutable arrays for the songArray (could do a little cleaner job of this here)
NSMutableArray *songArray = [[NSMutableArray alloc] init];
NSMutableArray *songTitles = [[NSMutableArray alloc] init];
//Add messy array to songArray then we can work with the songArray (maybe something better to do here)
for(id key in dict)
{
[songArray addObject:[dict objectForKey:key]];
}
//temp array to hold a messy array for all of the songTitles
NSArray *tempArray = [songArray valueForKey:#"songTitle"];
//go through the temparray and clean it up to make one array of all song titles and sort them
for (NSUInteger i = 0; i < [tempArray count]; i++) {
[songTitles addObjectsFromArray:[[tempArray objectAtIndex:i] sortedArrayUsingSelector:#selector(compare:)]];
}
//assign all song titles to our array of songTitles
self.allSongTitles = songTitles;
[dict release];
[allSongTitles release];
[songArray release];
[tempArray release];
[array release];
[super viewDidLoad];
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
I am sure there is probably a better way to do this but this is what I have come up with on my own. Thanks
If you have single array with the contents of all the letters, the rest is fairly simple. Iterate through the objects and call the dictionary method allKeys on each one. Each call to allKeys will return an NSArray containing the keys of that specific dictionary, which you can then place into another array.
EDIT
I made a mistake, didn't go deep enough. This is what I would do:
NSString *path = [[NSBundle mainBundle] pathForResource:#"songs" ofType:#"plist"];
NSDictionary plistDict = [NSDictionary dictionaryWithContentsOfFile:path]; //not using alloc and init means this isn't retained, so it will be autoreleased at the end of the method
NSArray *allLetterContents = [plistDict allValues]; // array of arrays, where each element is the content of a 'letter' in your plist (i.e. each element is an array of dictionaries)
NSMutableArray *allSongTitles = [[[NSMutableArray alloc] init] autorelease];
for(NSArray *oneLetterContents in allLetterContents)
{
for(NSDictionary *song in oneLetterContents)
{
[allSongTitles addObject:[song objectForKey:#"songTitle"]]
}
}
return allSongTitles;
This array isn't guaranteed to be sorted alphabetically, so you'll have to call [sortedArrayUsingSelector:] on it.
Reference:
NSMutableArray Class Reference
NSDictionary Class Reference