Unable to parse the response string using json parser - objective-c

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:#""];

Related

Unable to upload multipart file in karate, Required request part '' not present

ActualAPIRequest OutputFromKarate
Trying to upload a json file for an api using karate. Since api takes multipart input i am passing multipart configurations in karate.
But Required request part 'inputData' not present error is coming. Is there any solution for this please?
I have attached actual input and result from karate screenshot for reference
Just make sure that the data type of inputData and maybe swaggerFile is JSON. Looks like you are sending a string.
Please refer to this section of the doc: https://github.com/intuit/karate#type-conversion
If the server does not like the charset being sent for each multipart, try * configure charset = null

Encoded path is encoded again

I have to make a request:
* url foo
* path bar
* path code
Code is retrieved from another request and I receive it url encoded.
The problem is when I put it in the path, karate encode it again.
Ex: I receive zxc1J%2BV%2FMnb and in path it becomes zxc1J%252BV%252FMnb.
%2Bis replaced by %252B.
When I decode received code and put it in path, it is not encoded.
My javascript function to decode is :
* def codeDecoded = decodeURIComponent(code)
and encoding function is * def codeEncoded = encodeURIComponent(codeDecoded)
Am I missing smth? What is wrong? How can I manage this? Thanks.
Edit:
#Peter Thomas I try my last chance, because I already showed the prb to someone from server and he didn't understand why karate encodes again smth already encoded and doesn't encode smth decoded.
So my first request is a POST request, which returns an encoded code in responseHeaders. Ex: GVkX1%2FKZEi%2FWQ.
In my second request I have to take this code and put it in the path ex: url/GVkX1%2FKZEi%2FWQ.
The problem is that karate transforms it to url/GVkX1%252FKZEi%252FWQ . And I don't need it. And if I decode url/GVkX1%2FKZEi%2FWQ before to put it in path, the url in karate is url/GVkX1/KZEi/WQ. When put in path, the decoded code is not encoded in karate. I hope it is more understandable.
Yes Karate will always encode the path you provide for your convenience. This is what 99% of users expect anyways.
There is nothing wrong with using a custom function to decode and ensure you pass un-encoded URL / path values to Karate, so by all means, please continue to do so !
Edit: quite likely the way you tried to decode may be wrong, try this:
* def encoded = 'zxc1J%2BV%2FMnb'
* def decoded = java.net.URLDecoder.decode(encoded, 'UTF-8')
* print decoded
Which prints:
[print] zxc1J+V/Mnb

Restkit with bare json response objects

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.

How to set response headers with Rikulo Stream server?

I have one API that returns information in JSON, and for that, I would indicate that the content-type of the HttpResponse is application/json.
So, with Rikulo, I have something like :
connect.response.headers.set(HttpHeaders.CONTENT_TYPE, contentTypes['json']);
But when I request my API, it told me that the headers are immutable.
HttpException: HTTP headers are not mutable
#0 _HttpHeaders._checkMutable (http_headers.dart:267:21)
#1 _HttpHeaders.set (http_headers.dart:31:18)
Therefore, how can I set my response headers, or there is a native solution with Rikulo to return JSON data ?
You can set the contentType property directly:
connect.response.headers.contentType = contentTypes["json"];
If you'd like to set the header instead, you have to pass a String object (which Dart SDK expects):
connect.response.headers.set(HttpHeaders.CONTENT_TYPE,
contentTypes['json'].toString());
But the error message shall not be as you posted. Like Kai suggested in the comment, the message indicates you have output some data before setting the header.

objective c nsmutablerequest (httppost) with json converted to NSData as body but web api not recognizing

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!!!