I'm fairly new to Restkit but so far its worked pretty well for me using version 0.20.3 for most of my networking needs.
Im consuming a json based API written in c# using WCF webhttp bindings, it is worth mentioning at this point that I have absolutely no control of this API and cannot change the format of the returned json and I need to work with what I have.
The problem is that when the API returns a simple type like int, double or string as the response the json response is completely bare as below..
string response
"hello world"
int response
2342524
Both of these example responses have a content type of application/json
Ive tried to consume an API endpoint with restkit that gets a count of customer orders by the customer number.
The code for the request is as follows and Im expecting an NSNumber as the response but its generating an error as its a raw unwrapped type and I cant provide a mapping for this.
[manager getObject:nil
path:#"/service/http/CountOrders?CustomerId=324534413"
parameters:nil
success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult){
RKLogInfo(#"order count: %#",mappingResult);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
RKLogError(#"Operation failed with error: %#", error);
}];
And the error I'm getting back is
restkit.network:RKResponseMapperOperation.m:317 Failed to parse response data: Loaded an unprocessable response (200) with content type 'application/json'
restkit.network:RKObjectRequestOperation.m:213 GET 'http://CUSTOMERDOMAIN/service/http/CountOrders?CustomerId=324534413'
(200 OK / 0 objects)
[request=0.2263s mapping=0.0000s total=0.2386s]: Error Domain=org.restkit.RestKit.ErrorDomain Code=-1017 "Loaded an unprocessable response (200) with content type 'application/json'"
UserInfo=0x8e1a660 {NSErrorFailingURLKey=http://CUSTOMERDOMAIN/service/http/CountOrders?CustomerId=324534413, NSUnderlyingError=0x8e1b1a0
"The operation couldn’t be completed. (Cocoa error 3840.)",
NSLocalizedDescription=Loaded an unprocessable response (200) with content type 'application/json'}
hj
Is there any way of parsing the the response to an NSNumber to cover this edge case?
Im thinking a custom deserialization handler might be the way to go if thats at all possible but as I said I'm new to restkit and am basically looking for a push in the right direction.
A custom serializer could work, but a simple approach is probably to skip RestKit for the requests with 'simple' responses and use the underlying AFNetworking classes instead. Then you don't need to worry about serialization and you can just quickly coerce the response value.
Related
I’ve been working on a simple function with the serverless framework that gets some data in a http POST, does some analysis and sends the results back. I got it working locally on my machine using serverless-offline but when it comes to deploying it I’m getting an error parsing the event.body.
Logging out the event.body it’s a string that looks like this:
----------------------------267253304929569989286258
Content-Disposition: form-data; name="text"
TEST
----------------------------267253304929569989286258--
so it makes sense that the parse is failing but I have no idea why this error it happening.
Any suggestions? I’ve tried a bunch of different things but am completely stumped.
Thanks in advance!
You can't JSON.parse that event.body cause it isn't JSON. It looks like whatever POSTed that data is using a multipart form POST style request rather than sending JSON. How are you invoking the HTTP POST?
I had the same issue and after a lot of debugging noticed 2 important things:
1.When the content type is application/x-www-form-urlencoded you might need to parse the data in a different way:
const qs = require('querystring');
module.exports.run = async event => {
try {
const data = qs.parse(event.body);
console.info('DATA:', data);
} catch(e) {
console.error(e.message);
}
}
2.When the Content-Type of the request is multipart/form-data the parsing will be even more complicated. I will suggest extra dependency to parse it like multiparty or any other of your choice
Thank you #Brian Winant! I am putting the answer here as a screenshot so it's clearer. In Postman, do the following:
AWS Lambda would return event.body as encoded query strings if the content-type is x-www-urlencoded. To have it return a JSON string you can then parse, send JSON data and set content-type as application/json.
What does the Outpan server expect when posting data?
GET was giving me a json info that I was able to convert to an object.
Now when I'm giving information back just like the name:
https://api.outpan.com/v2/products/UPCCode/name?apikey=xxx
it will always not understand my information (error 400). Already tried sending the json back with additional info, "Foodname" and "name = Foodname"
I am trying to produce a request using afnetworking in objective c, however, it seems like the hardware that I am trying to connect to only applies requests when the parameters of the request are in a specific order. So I am wondering if there is a way to make the request so that the parameters are in a specific order. (As just doing it normally seems to jumble the sequence of the params up)
Here's my code:
NSDictionary *params = #{
#"param1" : #"bla",
#"param2" : #"bla2",
#"param3" : #"bla3"
};
[requestManager GET:#"somewhere" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
DLog(#"Success!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
DLog(#"Fail: %#", error);
}];
It actually goes to success every time, its just that the request I had applied would be practically ignored.
The actual request body becomes something like "param3=bla3¶m1=bla1¶m2=bla2 etc which would be ignored as it seems.
You can't do that using the request manager in the way you currently are.
Instead, you would need to create the parameter list yourself, and then create a request from that. Then you could use AFN to handle the request transmission and response.
Note that the server shouldn't require a specific order and that this should be changed if possible. Note also that the dictionary of parameters has no order (even though you add the keys in a set order).
Keeping the order of the parameters have a great impact on server performance. This sounds silly at first, but just think about GET requests which contain the query string as part of the URL. Web servers can cache the response for the given URL. If you mess with the order of the parameters, the cache won't be as effective as it could be.
The case is even worse if you call an API from different platforms (iOS, Android, Web) and they all reorder the params, which means that the same content will be found on 3 different cache keys.
Keeping the order is a performance issue at the first place.
I am using PHP services in my application i am getting the response from server i tried to parse the response string but JSON Parser returns NULL value. i am unable to parse this response string. i have goggling for this problem but no one give the exact solutions. i am using SBJson parser and NSJSONSeralization but it returns null value. i am posting my response string below please help me any one.
Response String is
([["{\"category_id\":\"1\", \"category_name\":\"BEVERAGES\", \"image_id\":\"6\"}"]])
Make sure that you parsing your json as in code below:
NSString * jsonString = #"{\"category_id\":\"1\", \"category_name\":\"BEVERAGES\", \"image_id\":\"6\"}";
NSData * jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
id jsonContainer = [NSJSONSerialization JSONObjectWithData:jsonData
options:NSJSONReadingMutableContainers
error:nil];
This response
([["{\"category_id\":\"1\", \"category_name\":\"BEVERAGES\", \"image_id\":\"6\"}"]])
is not proper JSON. It occurs, the server "wanted" to send JSON but didn't get it right ;) -- or you failed to print out a JSON correctly.
The JSON should probably look like:
[[{"category_id":"1","category_name":"BEVERAGES","image_id":"6"}]]
or
[[{"category_id":1,"category_name":"BEVERAGES","image_id":6}]]
Note: the key/value pairs might be reordered.
Additionally, ensure you specify the correct Accept header value, e.g. "application/json" in your request (caution: was incorrect before edit).
And, check status code (should be 200 (OK)) and the MIME type of the response before you attempt to parse the response with a JSON parser. If you expect JSON, you should get a Content-Type header (see also property MIMEType of the NSURLResponse) whose value should be application/json.
Best fix would be to fix it on the server end and encoded properly.
If this is not possible use [jsonString stringByReplacingOccurrencesOfString:#"\" withString:#""];
This is kinda a follow up question from this previous one:
https://stackoverflow.com/questions/16804632/ios-how-to-add-integer-and-null-into-json-post-using-nsmutablerequest-and-catch
Basically when I try to see what type of body the NSMutableRequest is sending I'm getting this:
json request is <7b224632 4964223a 2235222c 22496422 3a223122 2c225375
626d6973 73696f6e 54797065 4964223a 2230222c 22463149 64223a22
33222c22 4576656e 74496422 3a223522 2c224272 61636b65 74496422
3a223322 2c224631 53636f72 65223a22 30222c22 57696e6e 65724964
223a302c 22463241 6476223a 2230222c 224e6f74 6573223a 22686570
7070222c 2254696d 65223a22 4e554c4c 222c2246 3253636f 7265223a
2230222c 22463141 6476223a 2230222c 2257696e 42794964 223a2230 227d>
It's basically utf encoded. But that's the only type of object sethttpbody is accepting. I'm sending it to a MVC .Net Web Api. So I'm not sure if I need to do some type of conversion to recognize the json data sent from the iphone.
Also, whenever I would return an HttpResponseMessage from my web api, this part
NSLog(#"response is status code %ld with value %#", (long)[response
statusCode], [NSHTTPURLResponse localizedStringForStatusCode:[response
statusCode]]);
will only display this message
2013-05-30 23:30:53.882 Sammabiatch Admin[1156:c07] response is status
code 400 with value bad request
I was wondering how to get any other parts of the message as in .Net there are multiple properties for HttpResonseMessage. eg. StatusCode, ReasonPhrase, Content, Headers, RequestMessage and Version.
Any help is much appreciated. Thanks!!!