how to get objects from a json array in iphone? - iphone

I am working on an iPhone app which involves using json-framework.I am getting array using NSURL
[{"firstName":"X","lastName":"Y","id":1},{"firstName":"A","lastName":"B","id":2}]
How can i get these 2 objects as like if i query for id=1, the O/P is
id=1
firstName:X
lastName:Y
and putting it in a table.
I am googling the stuff from many days but didn't get any solution.
Please help me out , explanation through code is appreciated.
Thank You.

If your target SDK is ios4 or higher, you can use this project
https://github.com/stig/json-framework/
Once you add the source to your project, just
#import "SBJson.h"
and convert your Json string as follows
jsonResponse = [string JSONValue];
The method will fail if you don't have the full Json array in your string, but you can keep appending strings until it doesn't fail
To follow up for codejunkie's request below
you can assume in your data structure that the jsonResponse is an NSArray
In other implementations take care to test the response for NSArray or NSDictionary
NSArray * myPeople = [string JSONValue];
NSMutableDictionary * organizedData = [[NSMutableDictionary alloc] init];
for (NSDictionary * p in myPeople) {
[organizedData setValue:p forKey:[p valueForKey:#"id"]];
}
// now you can query for an id like so
// [organizedData valueForKey:#"1"]; and your output will be what you wanted from the original question
// just don't forget to release organizedData when you are done with it

https://github.com/johnezang/JSONKit
I use this to get data from a webservice that spits out 50 records each having another 20 internal elements similar to the one you specify...
I use the JSONKit in the following manner..(Had a look at SBJson a lot of user but i got confused from the word go.)
JSONDecoder *jArray = [[JSONDecoder alloc]init];
NSMutableArray *theObject = [[NSMutableArray alloc] init];
theObject = [jArray objectWithData:theResponseData];//objectWithString:theResponseString
NSMutableArray *csArray = [[NSMutableArray array] retain] ;
for(id key in theObject)
{
if([key valueForKey:#"firstName"] != Nil)
{
........
}
if([key valueForKey:#"lastName"] != Nil)
{
........
}
}
check it out and let me know if it works or not.. By the way Great responses guys... Good

Related

How to parse Json object

I'm stuck at json object parsing really tried hard. The problem is how to parse the json object. Here's what i get the response in the log.
{"0":{"**title**":"Test Event","url_title":"test_event1","status":"open","entry_date":"Sep 10, 2012,
05:20:38AM","entry_id":"26","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News &
Events","channel_name":"news_events","start_date":"1348120800","end_date":"1348120800","start_time": "43200","end_time":"46800","where":"FCF","news_event_description":"<p>\n\tLunch with group.<\/p>\n"},
"1":{"**title**":"Test Event 2","url_title":"test_event_2","status":"open","entry_date":"Sep 10, 2012, 05:20:08AM","entry_id":"28","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & Events","channel_name":"news_events","start_date":"1348207200","end_date":"1348207200","start_time":"43200","end_time":"46800","where":"FCF - Lunch","news_event_description":"<p>\n\tThis was a great event.<\/p>\n"},
"2":{"**title**":"Test Event 3","url_title":"test_event_3","status":"open","entry_date":"Sep 10, 2012, 05:20:54AM","entry_id":"29","site_id":"1","channel_id":"3","field_dt_40":null,"field_dt_58":null,"channel_title":"News & Events","channel_name":"news_events","start_date":"1346738400","end_date":"1346738400","start_time":"7200","end_time":"11700","where":"FCF - Lunch","news_event_description":"<p>\n\tFall planning season.<\/p>\n"}}
The problem is i want to show all the titles in the tableview. I can get the single Title by using key 0,1,2. But i want all the titles to be shown at once i parse
Please help me out guys, Thanks in advance.
Suppose jsonDict is your json dictionary.... Try this
NSArray * keys=[[NSArray alloc]init];
keys=[jsonDict allKeys];
NSMutableArray *titles=[[NSMutableArray alloc]init];
for(int i=0;i<[keys count];i++){
[titles addObject:[[jsonDict valueForKey:[keys objectAtIndex:i]]valueForKey:#"title"]];
}
NSLog(#"your array of titles : %#",titles); //use this array to fill your cell
Are you trying to parse the JSON yourself? You might find it easier to use something that's already well tested, such as TouchJSON or Apple's own NSJSONSerilization. The result should be a graph of Objective-C objects that you can use however you like.
In any case, what you've got there is the equivalent of a dictionary of dictionaries. If you have that as a NSDictionary called myJSONDictionary, you can say:
NSArray *theObjects = [myJSONDictionary allValues]; // gets all the objects
NSArray *theTitles = [theObjects valueForKey:#"**title**"]; // gets all the titles
You can also iterate through a dictionary using fast enumeration:
NSMutableArray *theTitles = [NSMutableArray array];
for (NSString *key in myJSONDictionary) {
NSDictionary *object = [myJSONDictionary objectForKey:key];
NSString *title = [object objectForKey:#"**title**"];
[theTitles addObject:title]
}
There's no real advantage to doing that instead of using KVC as in the first example if you just need the titles, but it could be the right choice if you have more complex work to do for each object.

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.

NSDictionary won't write to plist

I'm trying to write an NSDictionary with a complex structure to a plist for use in an iPhone app. However, the file doesn't seem to write at all, and I have no idea why.
This is what the structure should look like:
Level Dict
Roads Array
Road1 Array
Vertex1 Dict
x Number
y Number
Vertex2 Dict
...
And this is what my code looks like:
NSMutableDictionary *levels = [[NSMutableDictionary alloc] init];
NSMutableArray *roads = [[NSMutableArray alloc] init];
for(ChainLinkRoad *r in data.roads){
NSMutableArray *road = [[NSMutableArray alloc] init];
for(ChainPoint *p in r.v){
NSNumber *x = [NSNumber numberWithFloat: p.x];
NSNumber *y = [NSNumber numberWithFloat: p.y];
NSMutableDictionary *vertex = [[NSMutableDictionary alloc] init];
[vertex setObject:x forKey:#"x"];
[vertex setObject:y forKey:#"y"];
[road addObject:vertex];
}
[roads addObject:road];
}
[levels setObject:roads forKey:#"Roads"];
bool b = [levels writeToFile:#"test.plist" atomically:YES];
//returns true
I've tried converting the mutables to their immutable counterparts, but that didn't work. I'm able to access data from the final NSDictionary (levels) just fine.
Edit: I should add that this plist is not for actual use in the iphone game. It's for personal use when designing levels. The code won't exist in the final version.
A common problem is, that the dictionary isnt valid for string transformation like invalid UTF-8 characters. Make a output on the console to check it.
If that doesnt help you, save only some elements to see what is going on.
I just posted an answer for this same issue yesterday. Instead of trying to save out the individual data elements of a class save the entire object using NSKeyArchiver and NSCoding. Click the link for a full explanation.
How can I save Array of Class Objects in to a Plist(Iphone Development)

Passing returned data into array,iOS

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.

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];
}