I am having trouble with parsing/returning JSON from a URL response. Here is an example
lets say I submit this to a server [POST not GET]
firstname=first&lastname=last&age=99
and the response from the server is this
{
"person":{
"firstname":"first",
"lastname":"last",
"info":{
"age":"99"
}
}
}
how would I retrieve this information (certain elements)
lets say I JUST want the persons age so the return string should be just "99"
or how do I JUST return the lastname or JUST the firstname, another thing how would I pass the returned element into the next POST request without the user having to type it again?
if anyone can find an example that would be fantastic :)
Thank You!
lets say the name of this data is json (you called it response). This is a dictionary. What this means is that it has key/value pairs. To access it do the following:
To get any of this information in the dictionary, all you need is a one line of code!!
To get detail of a person's first name,
[response valueForKeyPath:#"person.firstname"];
To get last name :
[response valueForKeyPath:#"person.lastname"];
To get age :
[response valueForKeyPath:#"person.info.age"];
Hmm... If it were me, I would just get the NSDictionary, then look inside the NSDictionary.
To get age:
You would want to get { "firstname":"first", "lastname":"last", "info":{ "age":"99" } }, so do:
[responseObject objectForKey:#"person"];
After you do that, you would want to get { "age":"99" }. To do that, you should use
[[responseObject objectForKey:#"person"]objectForKey:#"info"];
After that, 1 last step to get the value for age:
[[[responseObject objectForKey:#"person"]objectForKey:#"info"]objectForKey:#"age"];
And then, you have age.
To get firstname
Just find the object for key firstname by doing:
[[responseObject objectForKey:#"person"]objectForKey:#"firstname"];
To get lastname
[[responseObject objectForKey:#"person"]objectForKey:#"lastname"];
... The rest should follow the same rule.
How to pass it back to a POST request
Well, the POST request takes in an id parameters. This is where you would put the dictionary. To do this correctly without having to deal with any asynchrony, you would have to make the POST request inside the GET request. For example:
[manager GET:<your GET url>
parameters:nil
success:^(AFHTTPRequestOperation *operation, id responseObject) {
[manager POST:<your POST url>
parameters:responseObject
success:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(#"Success!"); }
failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(#"Error: %#", error); }];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(#"Error: %#", error); }];
Well, that's pretty much it. Hope this helped :)
Related
I've just started accessing TMDB for an iOS app using https://github.com/JaviLorbada/JLTMDbClient - I searched for a solution using relevant search terms before posting and didn't see any other questions asked about this.
When I use the author's example code it works as it should and fetchedData contains a list of popular movies:
[[JLTMDbClient sharedAPIInstance] GET:kJLTMDbMoviePopular withParameters:nil andResponseBlock:^(id response, NSError *error) {
if(!error){
fetchedData = response;
NSLog(#"Popular movies: %#", fetchedData);
}
}];
What I need is to return a list of movies for a specific actor (stored in variable 'name', defined as an NSString). I read the documentation on Github and also TMDB.com to understand the syntax, but I just can't seem to get it.
I tried (unsuccessfully, no error but nothing posted from NSLog):
[[JLTMDbClient sharedAPIInstance] GET:kJLTMDbPerson withParameters:#{#"id":name} andResponseBlock:^(id response, NSError *error) {
if(!error){
fetchedData = response;
NSLog(#"Actors movies: %#", fetchedData);
}
}];
Also I'm unsure which of the following I should be using:
kJLTMDbPerson
kJLTMDbSearchPerson
Thanks in advance for any responses.
I am considering using AFNetworking in one of my projects. But I have a problem.
Here is the code:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
// manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:completeUrlString parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"%#", responseObject);
} failure:nil];
The problem Is the respose object. It is a dictionary with only a value inside. The value is shown to be a NSObject! That should actually be a NSDictionary with several key/value pairs.
Here is the raw json:
{
"signInResponse": {
"userName": "971777771554300",
"duration": 315360000000,
"token": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"userId": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"idleTimeout": 2592000000
}
}
Why does the parser fail? Also I would like to note that the url does not end in ".json" as it is dinamically created.
Another small question: several resposes return json objects where the keys that need to be in the
response dictionary are of the form "#importantKey" or "#key". I remmember that some parsers can't returns such keys in their response, is this a problem for AFNetworking?
if you use alamofire, this little snippet can help, maybe you need to do casting like this :
var innerData = data!["signInResponse"]!!
var innerData2 = innerData[0]
var DataDict = (innerData2 as! NSDictionary) as Dictionary
self.userName = DataDict["userName"]! as! String
I have problem with my below funct:
NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
sportid, #"sport",
country, SC_PAIS,
team, SC_TEAM,
token, SC_TOKEN,nil];
[[SCHTTPClientServer sharedClient] setParameterEncoding:AFJSONParameterEncoding];
[[SCHTTPClientServer sharedClient] putPath:#"calendarelemfilters/teams" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"RESPonsee %#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"ERROR %#",[error localizedDescription]);
}];
this is my code. I have below error- How can i fix it?
Thanks
"""RESPONSE STRING: <>Apache Tomcat/7.0.26 - Error report HTTP Status 400 - Required String parameter 'token' is not presenttype Status reportmessage Required String parameter 'token' is not presentdescription The request sent by the client was syntactically incorrect (Required String parameter 'token' is not present).Apache Tomcat/7.0.26
2013-09-19 13:10:24.254 ISportsCal[834:907] ERROR Expected status code in (200-299), got 400"""
It's all there in the error message. The server is expecting a parameter called token and you aren't passing one in the expected format.
What is SC_TOKEN? Possibly a capitalization error?
Are you sure the server is expecting JSON?
Is the server expecting any additional headers?
You may want to download https://github.com/AFNetworking/AFHTTPRequestOperationLogger to take a look at your requests. You can download a tool like Postman REST Client, get the put request working there, and then make sure your AFNetworking request matches this.
I have fixed it with postPath. and also i setted "setparameter encoding" as below.
[[SCHTTPClientServer sharedClient] setParameterEncoding:AFFormURLParameterEncoding];
Thanks
I have one service REST/JSON. It looks like:
#GET
#Produces(MediaType.TEXT_PLAIN)
#Path("/login/{userName}/{password}")
public synchronized String login(#PathParam("userName") String userName,
#PathParam("password") String password);
How do I consume this using RestKit in IOS?
It's obvious that in order to send canonical restkit requests you ought to have entities, mappings etc. Documentation provides explicit answer of how to do it.
I can also suggest you using the easy way:
[[RKObjectManager sharedManager].HTTPClient postPath:#"your URL string" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"WHOOO");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//
}];
responseObject is what you need.
So I'm relatively new to this and I'm running into a problem that has me pretty stumped. SimpleUPC provides a pretty simple API but they have the following format for a JSON request:
{
"auth":"Your API Key",
"method":"MethodName",
"params": {
"paramName":"paramValue",
"paramName2":"paramValue2",
},
"returnFormat":"optional"
}
I also download their Ruby sample which I have verified does work from the command line.
# Sample API calls using JSON...
host = "api.simpleupc.com"
path = "/v1.php"
# An example query for FetchProductByUPC method
request = {
"auth" => 'Your-API-Key',
"method" => 'FetchProductByUPC',
"params" => {"upc" => '041383096013'}
}
json = request.to_json()
response = Net::HTTP.start(host) { |http|
http.post(path, json, initheader = {'Content-Type' =>'text/json'})
}
output = response.body
puts output
Ok so far so good. But here's my code that is trying to do the same thing but I am getting errors complaining about missing parameters.
NSDictionary *requestDict = #{#"auth": kSimpleAPIKey, #"method": #"FetchProductByUPC", #"params":#{#"upc": code}};
[[SimpleUPCClient sharedClient] getPath:#""
parameters:requestDict
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Response: %#", responseObject);
}
failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[TMReportingHandler handleError:error fatal:NO];
}];
I know this has got to be something simple I'm doing wrong but I can't figure it out. Anyone?
Wow, I knew it was something simple. Turns out it was expecting a POST instead of a GET...I switched it and it worked immediately.