How to parse the JSON response? - iphone

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.

Related

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

how to get objects from a json array in 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

What should the return value of a JSON GET or POST look like?

I'm new to JSON and just starting to wrap my head around it's functionality.
I'm trying to see if I can get print some data from some JSON methods. I've been alternating between the first one and the one that is commented out. The ideas is to see if I can get anything printing:
id newConnection = [scAPI performMethod:#"GET" onResource:#"me/connections.json" withParameters:nil context:nil userInfo:nil];
// id newConnection = [scAPI performMethod:#"POST"
// onResource:#"connections"
// withParameters:[NSDictionary dictionaryWithObjectsAndKeys:
// #"facebook_profile", #"service",
// #"imc://connection", #"redirect_uri",
// #"touch", #"display", //optional, forces services to use the mobile auth page if available
// nil]
// context:nil
// userInfo:nil];
NSLog(#"newConnection %#", newConnection);
NSLog(#"Is of type: %#", [newConnection class]);
NSDictionary *dict = [newConnection objectFromJSONString];
for (id key in dict) {
NSLog(#"key: %#, value: %#", key, [dict objectForKey:key]);
}
The above code doesn't err and I get logs such as:
Does this look right? How do I properly use these JSON methods to get a dictionary of values?
EDIT 1
To be clear I'm using JSONKit :)
I would personally recommend using the SBJSON library. Getting a dictionary with it is straightforward.
Get a response back from a connection, and then use the following code (where response is an NSString containing the response from the server):
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSArray *returnData = [parser objectWithString:[response stringByReplacingOccurrencesOfString:#"\\\\" withString:#"\\"]];
[parser release];
NSDictionary *returnDict = (NSDictionary *)returnData;
This is unrelated, but for examining JSON data, I would also recommend Online JSON Viewer. You can paste in your JSON strings and view it with a collapsable array structure. Very convenient.

How to extract the actual NSString from json object as NSArray

I'm working with a large set of json and really just need the NSString representation of what's inside the NSArray -including all the { }
My question is this - is their a better way than simply looping through each NSArray inside the main NSArray and outputting the description one by one?
ie- the below is a start to this process but it's very brittle meaning I need to know each item inside the hat {} and this isn't something I actually care about. I just need the json string to move forward.
The working code is below (thank you in advance!)
NSString* responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSArray* json = [responseString JSONValue];
NSArray* item = [json valueForKeyPath:#"d.data"];
NSArray* hatjson = [item objectForKey:#"hat"];
NSMutableString * result = [[NSMutableString alloc] init];
for (NSObject * obj in hatjson)
{
[result appendString:[obj description]];
}
NSLog(#"the hat json is .. %#", result);
// …
NSArray* hatjson = [item objectForKey:#"hat"];
NSString *result = [hatjson JSONRepresentation];
NSLog(#"the hat json is .. %#", result);
I’m assuming you’re using SBJSON for JSON parsing. SBJSON defines a category on NSObject that includes the method
- (NSString *)JSONRepresentation;
This method returns a string with the JSON representation of a given object so long as the object is an instance of a class which SBJSON can convert to JSON (e.g. strings, numbers, arrays, dictionaries).
I'm assuming you're using the JSON library from here: https://github.com/stig/json-framework
You're complaining that the code you provided is brittle, but it sounds like, for what you want, the situation is brittle, so I think it's ok for the code that access it to be brittle, as long as you put NSAsserts in there so that you know ASAP when your assumptions have been broken.
I think the most brittle aspect of the code you've shown is that it assumes you're getting back NSArrays, when it appears from how you're accessing it that it's actually giving you NSDictionaries.
For instance, reading your code, I conclude that the responseString represents a JSON nested map looking something like this:
{ "d": { "data": { "hat": "baseball cap" } } }
The question then is "do you ever expect the value corresponding to the "hat" key to ever have more than one value?" I would genericize this code like so:
NSString* responseString = [[[NSString alloc] initWithData: responseData encoding: NSUTF8StringEncoding] autorelease];
[responseData release];
id json = [responseString JSONValue];
id hatJSONValue = [json valueForKeyPath:#"d.data.hat"];
NSString* result = nil;
if ([hatJSONValue isKindOfClass: [NSArray class]] && [hatJSONValue count] == 1)
{
result = [[hatJSONValue lastObject] description];
}
else
{
NSAssert(NO, #"Assumptions about returned JSON were wrong.");
}
NSLog(#"the hat json is .. %#", result);
Generally speaking, you always have to make tradeoffs between writing non-brittle code and getting things done. The key should be that if your code is going to make assumptions, you should assert that they're true, so if the situation ever changes, you'll know!