How to read JSON object - iphone

I have a JSON object like
{"status":"200","id":"23","username":"nipinponmudi#gmail.com","fname":"hh","laname":"hh","timezone":"2","createdate":"2011-09-20 22:05:24","key":"db3f57a8f2b9abd9d51916232f5a77b9"}
The object above is a response from a server.I want to display these objects in corresponding textfields on the viewdidload method.I want to read this object and display separately in textfields.I need to extract the username,fname,lname only.No need to read the status

take a look at https://github.com/stig/json-framework/ . I'm sure they are so many source and example out there to show you.
NSString *jsonString = #{"status":"200","id":"23","username":"nipinponmudi#gmail.com","fname":"hh","laname":"hh","timezone":"2","createdate":"2011-09-20 22:05:24","key":"db3f57a8f2b9abd9d51916232f5a77b9"}";
SBJsonParser *parser = [SBJsonParser new];
id object = [parser objectWithString:jsonString];
txtName.text = [object objectForKey:#"username"];

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.

NSMutableData Plist for NSMutableDictionary

I am loading a plist via NSURLConnection into NSMutableData.
After that is done I want to read the PLIST into a NSMutableDictionary.
And then add the objects into my array to display them in a tableview.
But at the moment I don't know how to extract the data from NSMutableData into my NSMutableDictionary.
If I save the data local as plist on the iPhone in some folder and then read the plist into my Dictionary it works. But isn't there a way to do this directly?
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
receivedData = [[NSMutableData alloc] initWithData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSData *data = [[NSMutableData alloc] initWithData:receivedData];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [unarchiver decodeObjectForKey:#"Beverage"];
[unarchiver finishDecoding];
beverageArray = [[NSMutableArray alloc] init];
beverageArray = [myDictionary objectForKey:#"Beverage"];
NSLog(#"%#", beverageArray);
}
Before using NSURLConnection I used this which works:
- (void) makeDataBeverage {
beverageArray = [[NSMutableArray alloc] init];
NSMutableDictionary *beverageDic = [[NSMutableDictionary alloc]initWithContentsOfURL:[NSURL URLWithString:NSLocalizedString(#"beverage", nil)]];
beverageArray = [beverageDic objectForKey:#"Beverage"];
Now I want to the same with using NSURLConnection.
Assuming you have the complete data(*), you'll want to look into the NSPropertyListSerialization class. Its +propertyListWithData:options:format:error: method should get you what you're looking for, and you can use the options parameter to get the results as a mutable dictionary or array.
(*)It sounds like you have the complete data, since you say you can write it to a file and then read it in using dictionaryWithContentsOfFile: or similar, but it doesn't look like you're guaranteed to get it from the code you've shown. You're creating a new data in -connection:didReceiveData:, but that delegate method can be called multiple times as the data arrives in pieces. (I'm guessing it just happened to arrive all in one piece for your testing... this may not always be true, especially on a mobile device.) Instead, you probably want to create an empty mutable data when you start your NSURLConnection (or in -connection:didReceiveResponse:), append to it in -connection:didReceiveData:, and parse it in -connectiondidFinishLoading:. Or even better, since the property list parser can't do anything with a partial data anyway, use the new +[NSURLConnection sendAsynchronousRequest:queue:completionHandler:] if you're targeting iOS 5.0+.

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.

convert Core Data NSManagedObject in to JSON on iPhone?

I was to post some of my COre Data objects back to a web service and would like to send them as JSON. I am receiving objects from the server a JSON using this library:
http://code.google.com/p/json-framework/
But I cannot figure out how to change my objects back to JSON?
To create json from you r objects, you have to build an NSDictionary from your object, and then convert to string with the SBJsonWriter class.
NSDictionary *jsonDictionary = [NSDictionary dictionaryWithObject:(NSArray *)YourArrayOfElements forKey:#"objects"];
SBJsonWriter *jsonWriter = [SBJsonWriter new];
//Just for error tracing
jsonWriter.humanReadable = YES;
NSString *json = [jsonWriter stringWithObject:jsonDictionary];
if (!json){
NSLog(#"-JSONRepresentation failed. Error trace is: %#", [jsonWriter errorTrace]);
}
[jsonWriter release];
NSData *data = [json dataUsingEncoding:NSUTF8StringEncoding];
And then you can set as your post request's body.
If you would like a more full-featured solution that what is offered by a standalone parsing library, you may want to take a look at RestKit: http://restkit.org/
The framework wraps the operations of fetching, parsing, and mapping JSON payloads into objects. It also allows you to update remote representations by POST/PUT'ing the objects back with a request. By default, outbound requests are form-encoded but the library ships with a class for using JSON as the wire format for posting back to the server.
At a high level, here's what your fetch & post operations would feel like in RestKit:
- (void)loadObjects {
[[RKObjectManager sharedManager] loadObjectsAtResourcePath:[#"/path/to/stuff.json" delegate:self];
}
- (void)objectLoader:(RKObjectLoader*)loader didLoadObjects:(NSArray*)objects {
NSLog(#"These are my JSON decoded, mapped objects: %#", objects);
// Mutate and PUT the changes back to the server
MyObject* anObject = [objects objectAtIndex:0];
anObject.name = #"This is the new name!";
[[RKObjectManager sharedManager] putObject:anObject delegate:self];
}
The framework takes care of the JSON parsing/encoding on a background thread and let's you declare how attributes in the JSON map to properties on your object. Mapping to Core Data backed classes is fully supported.