retrieving certain keys from a returned JSON in Objective C - objective-c

I am sending a JSON encoded POST type to a server of mine which reads the sent information in PHP and decodes it there. Now when I re-encode it and send it back it works perfectly and I can NSLog the response but my issue is how do I get a specific section of the response?
Here is an example response:
responseString: {"status":"ok","code":0,"original request":{"username":"test"
`,"password":"test"}}`
Suggestions, thoughts?

What you are receiving is actually a 'dictionary of objects'. You can separate the data in the above code as follows:
First, serialize the response data using JSON serialization as follows:
NSError* error;
NSDictionary* responseDictionary = [NSJSONSerialization JSONObjectWithData:returnData options:nil error:&error];
You may then separate the dictionary as you wish.For instance, if you want to retrieve the value for "status", you may use:
NSString *status = [responseDictionary objectForKey:#"status"];
Or, if you want to retrieve "original request" which is another dictionary, you may use:
NSDictionary *originalRequest = [responseDictionary objectForKey:#"original request"];
Hope this helps!

The response received from the server is JSON data.
Here is an excellent tutorial on JSON parsing for iOS and there are plenty of tutorials & docs if you browse.
http://www.raywenderlich.com/5492/working-with-json-in-ios-5
In JSON, "{}" represents a dictionary and "[]" is an array. So, try this
NSDictionary* originalRequest = [responseString objectForKey:#"original request"];
you can dig in further like this,
NSString* username = [originalRequest objectForKey:#"username"];
I strongly recommend you to read some tutorials on JSON.

Related

How to send JSON-data in post request Objective-C?

I get an error while I send Json data to server. I used the following code to change the NSMutableDictionary To JSON.
NSString* jsonString1 = [postDict JSONRepresentation];
NSLog(#"%#",jsonString1);
JSON Format:
{"user_email":"gupta.nivrit#gmail.com","firstname":"nivrit","user_password":"1234","confirm_passward":"1234"}
I use the following method to send this JSON format to server:
NSMutableDictionary *responseDict =
(NSMutableDictionary *)[[mWebServiceHelperOBJ
makeCallToURL:#"register.php"
withDataPost:jsonString1] JSONValue];
When I implemented this code I received this issue
incompatible pointer type sending NSString to parameter of type NSMutableDictionary.
If your method
- (NSString *)makeCallToURL:(NSString*)url withDataPost:(NSMutableDictionary*)dict;
is the same as in this question: Uploading PDF file through JSON Web Service, then the JSON encoding of the request data is done inside
that method, so you should call it directly with the postDict,
and not with the JSON string jsonString1:
NSMutableDictionary *responseDict =
(NSMutableDictionary *)[[mWebServiceHelperOBJ makeCallToURL:#"register.php"
withDataPost:postDict] JSONValue];
(This assumes that postDict is an NSMutableDictionary.)

Cocoa Touch JSON Handling

I've been looking for a while now and I can't seem to find a solution.
I am trying to format a JSON object that is being held in an NSData *receivedData.
The format of the JSON is:
[
{
"name":"Stephen",
"nickname":"Bob"
},
{
"name":"Rob",
"nickname":"Mike"
},
{
"name":"Arya",
"nickname":"Jane"
}
]
Normally I would use "NSJSONSerialization JSONObjectWithData:" of the NSDictionary. Then I would normally take the root of the JSON (in this case it would be something like "People":) and create the array from that root object. However as you can see this response is simply an array without a root object. I'm not sure how to handle this. The end goal is to have an array of Person objects, populated with the data in the JSON.
Edit: I would also like to add that I want to keep it native without third party libraries.
OK for anyone reading this. I just figured it out. Instead of formatting the initial NSData into a dictionary, you put that straight into an array. Then create a dictionary for each object in the array. Like so:
NSArray *response = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSDictionary* json = [responseArray objectAtIndex:0];
NSLog (#"%#",[json objectForKey:#"nickname"]);

RestKit PUT not working

I'm trying to do a fairly basic HTTP PUT using RestKit. I don't want to put the entire object, since the API call was designed to accept a single query parameter and just update that field. I've tried two approaches so far, both unsuccessful.
URL to post to: https://myserver/api/users/{userId}
Query string parameter: verificationCode=
Example usage: PUT https://myserver/api/users/101?verificationCode=646133
Approach #1: Put the query parameter in a RKParams object and make the PUT call with those params.
NSString *putUrl = [NSString stringWithFormat:#"/api/users/%i", [APIUserInfo sharedAPIUserInfo].apiUserIdx];
NSLog(#"the PUT url is %#", putUrl);
// Send a PUT to a remote resource. The dictionary will be transparently
// converted into a URL encoded representation and sent along as the request body
NSDictionary* paramsDict = [NSDictionary dictionaryWithObject:[_verificationCode text] forKey:#"verificationCode"];
// Convert the NS Dictionary into Params
RKParams *params = [RKParams paramsWithDictionary:paramsDict];
[[RKClient sharedClient] put:putUrl params:params delegate:self];
Approach #2: Build the entire url and try a PUT with params set to nil.
NSString *putUrl = [NSString stringWithFormat:#"/api/users/%i?verificationCode=%#", [APIUserInfo sharedAPIUserInfo].apiUserIdx, [_verificationCode text]];
NSLog(#"the PUT url is %#", putUrl);
[[RKClient sharedClient] put:putUrl params:nil delegate:self];
Neither approach is working for me. The first fails saying "RestKit was asked to retransmit a new body stream for a request. Possible connection error or authentication challenge?" then runs for about 10 seconds and times out. The second approach fails saying HTTP Status 405 - Method Not Allowed.
Can anyone point out where I'm going wrong, or provide me with a simple PUT example using RestKit? Most of the examples I've found at there are putting the entire object which I don't want to do in this case.
UPDATE:
Approach #2 worked well once I got a few things sorted out on the server side. Final solution:
NSString *putUrl = [NSString stringWithFormat:#"/api/users/verify/%i?verificationCode=%#", [APIUserInfo sharedAPIUserInfo].apiUserIdx, [_verificationCode text]];
NSLog(#"the PUT url is %#", putUrl);
[[RKClient sharedClient] put:putUrl params:nil delegate:self];
the HTTP PUT method is disabled on your webserver. It is by default on all webserver for security reasons.
HTTP Status 405 - Method Not Allowed.

Send post request in XML format using RestKit

Hi I am using restkit for first time, and there are several questions that come to my mind. First when sending a post request using restkit what format is the request Json or XML and how can I specify it? I am sending a post request to the server to authenticate a user and should receive a conformation if details correct in XML format.
NSArray *objects = [NSArray arrayWithObjects: email, password, nil];
NSArray *keys = [NSArray arrayWithObjects:#"username", #"password", nil];
NSDictionary *params = [NSDictionary dictionaryWithObjects:objects forKeys:keys];
[[RKClient sharedClient] post:#"/login" params:params delegate:self];
This is the code I am using, the xml accepted by the web services should look like
<login>
<username>user#example.com</username>
<password>Password</password>
</login>
It is sending the request,but I am not getting the right response. Is there a way to view what is the format of the request I am sending to the server ?
Sounds like you are using the wrong call. The post call you are using assumes that the rest service wants params like login=username&password=skdjgh, i.e. NOT in XML, but in 'normal REST format'. You need to either find a call to post a block of text using RestKit, or use another call. In other words you need to create the XML yourself (or use some library) then send that via a post.
Give this a try. I think it is supposed to do what you want. I never got it to work but I had other things wrong with my code.
RKObjectManager* objectManager = [RKObjectManager objectManagerWithBaseURL:#"http://mysite.com"];
objectManager.serializationMIMEType = RKMIMETypeXML;
Note: this may be what you do for sending XML back to you, not sending XML to the server. Don't know off the top of my head.
You can use RKRequestSerialization class to do the xml serialization for you.
Here is a code snippet from one of my projects:
#import <RestKit/RKRequestSerialization.h>
...
[RKObjectManager sharedManager].acceptMIMEType = RKMIMETypeTextXML;
NSString *loginData = #"<Login><UserId>test</UserId><Password>test</Password></Login>";
[[RKClient sharedClient] setValue:#"XYZ01" forHTTPHeaderField:#"ServiceId"];
[[RKClient sharedClient] post:#"/login"
params:[RKRequestSerialization serializationWithData:[loginDetails dataUsingEncoding:NSUTF8StringEncoding] MIMEType:RKMIMETypeTextXML]
delegate:self];
And, here is the dump using RKLogConfigureByName("RestKit/Network", RKLogLevelTrace)
2012-08-12 11:28:41.476 MyApp[730:707] T restkit.network:RKRequest.m:402 Prepared POST URLRequest '<NSMutableURLRequest https://someserver.com/MyApp/rest/service/request>'. HTTP Headers: {
Accept = "text/xml";
"Content-Length" = 75;
"Content-Type" = "text/xml";
ServiceId = XYZ01;
}. HTTP Body: <Login><UserId>test</UserId><Password>test</Password></Login>
I did objectManager.serializationMIMEType = RKMIMETypeXML; but the Content-Length of my request is 0, and the HTTP Body is empty. If I use RKMIMETypeJSON the request looks fine, but the xml serialization doesn't work. Any ideas why this happens? What else do I need to do to post xml with valid serialization?
I also found this in doc: "RestKit currently supports serialization to RKMIMETypeFormURLEncoded and RKMIMETypeJSON". So, how can I use RKObjectManager to post xml?
I solved this using ASIHTTPRequest and XMLWriter. Unfortunate, but RestKit just doesn't seem to support XML posts out the box.
I do use RK for GETting stuff though.

parsing JSON using objective C?

I have spent 1 week studying objective C. Now I am quite confused at the dealing with data part.
My friend gave me a link
http://nrj.playsoft.fr/v3/getQuiz.php?udid=23423455&app=2
and ask me write a class to parse this JSON. I had no clue what parsing JSON means. but I have gone online and looked up. I could understand a basics of it and then I impletemented a punch of code to parse this JSON. Which is:
-
(void)parseURL
{
//create new SBJSON object
SBJSON *parser = [[SBJSON alloc] init];
NSError *error = nil;
//perform request from URL
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://nrj.playsoft.fr/v3/getQuiz.php?udid=23423455&app=2"]];
// Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
// Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
// parse the JSON response into an object
NSDictionary *results = [parser objectWithString:json_string error:&error];
// array just for the "answer" results
NSArray *quizes = [results objectForKey:#"quiz"];
NSDictionary *firstQuiz = [quizes objectAtIndex:0];
// finally, the name key
NSString *extract = [firstQuiz objectForKey:#"extract"];
NSLog(#"this is: %#", [extract valueForKey:#"extract"]);
}
This is at the implementation file, but in the header file I could not declare any variables, it will print out some errors. I tried to run this, there is no errors, but I am not sure this code is correct or not. And my friend asked me to write a class into an existing project. I don't know what needs to be modified and what not. I am so blur right now. Could anyone pro in this give me a hand. ?
My sincere thanks.
Thanks for reply. I have downloading and added the JSON framework ealier too. I am just not sure where to begin and where to end, meaning the step I should do when I add JSON framework into it. I could understand the syntax but I am not sure about the steps I should do. I am a newbie in this.
If you support iOS 5.0+, you should use built-in NSJSONSerialization.
It is faster than TouchJSON.
You could just use TouchJSON: http://code.google.com/p/touchcode/wiki/TouchJSON
Or you could use this one: http://code.google.com/p/json-framework/
I'm sure there are others. I use TouchJSON... it's fast and has a good API.
I recommend working through Ray Wenderlich's MapKit tutorial, especially if you are a newbie. It covers several common iOS development issues, including parsing JSON data.
http://www.raywenderlich.com/2847/introduction-to-mapkit-on-ios-tutorial
"The Implementation" section is where his JSON feed is retrieved and then in "Plotting the Data" he uses the SBJson library to parse it.