AFNetworking error parsing JSON - json

I'm using AFNetworking 2.3 API to fetch currency exchange rates which returns JSON. In addition to HTTP the API also supports HTTPS. I'm using a subclass of AFHTTPSessionManager and set the response serializer to AFJSONResponseSerializer.
If I use HTTP everything works as expected, however once I use HTTPS, I receive the following error
Error Domain=NSCocoaErrorDomain Code=3840 "The data couldn’t be read
because it isn’t in the correct format." (JSON text did not start with
array or object and option to allow fragments not set.)
UserInfo=0x60000046c700 {NSDebugDescription=JSON text did not start
with array or object and option to allow fragments not set.}
I checked the response data and it appears identical to the HTTP response. Also the response code is 200 and the header indicates
"Content-Type" = "application/json; charset=utf-8";
If I entry the url directly into safari the data appears as expected. I also tried setting the reading options of the response serializer to NSJSONReadingAllowFragments, but no change.
Is this a server side issue? What else could I do to debug this?

Related

POST in JMeter gives "Unrecognized token 'json'"

I can not figure out why I get this error:
"Failed to parse request body as JSON resource. Error was: Failed to parse JSON encoded FHIR content: Unrecognized token 'json': was expecting ('true', 'false' or 'null')\n at [Source: UNKNOWN; line: 3, column: 29]"
FHIR is the standard used. I also tested with a valid JSON that worked with Postman, so I don't think the actual JSON is the issue.
I'm not sure if I'm correct, but it seems JMeter adds 'json' from somewhere as the error states the token 'json' is unexpected. This is the Request > Request body tab in View Results Tree.
This is just a test JSON, but I got the same response with a JSON body that is working in Postman (and I formatted correctly to be sure). I have the Content-Type header specified. I simply don't understand where the token 'json' would come from as my json itself doesn't contain the token. Does anybody know if JMeter adds something to the request?
You're sending incorrect payload, it should look like:
{
"test" : "X"
}
and you are sending
{
"test" : "X"
}json
^^^^ this guy is causing the issue
JMeter doesn't add anything to request, you need to double check your configuration, i.e. JMeter jmx scripts are "normal" XML files so you can use your favorite text editor to look up this json
If you're able to send a valid request using Postman you should be able to record it using JMeter's HTTP(S) Test Script Recorder, just configure Postman to use JMeter as the proxy and run your request/collection - JMeter will capture the requests and generate relevant HTTP Request samplers which can be replayed successfully.
More information: How to Convert Your Postman API Tests to JMeter for Scaling
It happened to be that if you add a default parameter in an HTTP Request Defaults (in my case _format=json), it would add it to the body of the POST.
I fixed this by adding a BeanShell PreProcessor with the code:
if(sampler.getMethod().equalsIgnoreCase("get")){ sampler.addArgument("_format", "json"); }

How to enforce "accept" OR " format" parameters in HTTP URL to enforce XML response from server than a JSON

I am always getting JSON response for my HTTP request to access one ORDS-Oracle Rest Data Services API:
http://localhost:8080/ords/hr/employees/
However my requirement is to get XML response. I tried to choose XML from drop down list available at POSTMAN, however content is not changing to XML.
I need a way to specify parameter as part of HTTP URL so that response is XML than JSON and I tried to change URL like below:
Way1:
http://localhost:8080/ords/hr/employees?format=xml
Way2:
http://abcdef.us.oracle.com:8001/claims-ws/api/generic/lineofbusinesses/421?Content-Type:application/xml
Way3:
http://abcdfef.us.oracle.com:8001/claims-ws/api/generic/lineofbusinesses/421?Accept:application/xml
Way4:
http://abcdef.us.oracle.com:8001/claims-ws/api/generic/lineofbusinesses/421?Accept=application/xml
However nothing is working and response is always JSON.
Any suggestion?

Get JSON from Flask request only if it is valid

I know that there are nice modules (like the validator-collection) that can check if a JSON is valid. But in my case, I want to achieve this with the built-in Flask capabilities: is_json() and get_json().
This is what I have tried:
import flask
def get_json_data():
if flask.request.is_json():
try:
data = flask.request.get_json()
except(ValueError):
# get_json failed, return None
# handle ValueError
else:
# is_json failed, return None
# handle ValueError
After reading the docs, I could only find the ValueError exception being raised. If that is indeed the only exception, is my approach above correct in handling it and making sure that a data will hold JSON data only when a valid JSON request has been made?
The documentation states that .is_json() only checks if the request has a Content-Type that would indicate that the request contains JSON data.
property is_json
Check if the mimetype indicates JSON data, either application/json or application/+json*.
It does not check whether the request data is actually JSON, so this check's usefulness is limited. When the client sends JSON but does not set an appropriate Content-Type header, or sets the header but sends invalid JSON, you learn nothing from .is_json().
However, .get_json() does a "contains valid JSON" check: It tries to parse the request data as JSON, and either that works, in which case it returns the data, or it fails, in which case it throws an error. By default, .get_json() internally calls .is_json() anyway.
For what you want to do, I would say this is sufficient.
def get_json_data():
data = flask.request.get_json()
If parsing is unsuccessful, there is no error thrown (compare werkzeug docs). Instead "Bad Request" is returned to the client. If you want to change that behavior, override the Request.on_json_loading_failed() method with your own version.

Node.js express res.json behavior

I have been working on one of my projects using node and ng4
when I came across using res.json to send an array back to Angular 4 front end, like res.json(arrayResult). Surprisingly, I cannot use JSON.parse(arrayResult) after Angular receives it because it throws an error saying unexpected end of input. I however can access all the data through result[i], just like any normal array.
I don't quite understand why res.json() does not send my array as a string to the front end. Is there any internal conversion involved? Why I could access the content through index without even parsing it or doing any conversion with it?
The server indeed send your json data as a string. Additionally to the string, the server passes Content-Type header to your client which tells your client what kind of data you received.
So if the Content-Type was text/html your client would think that he received an HTML file.
In your case, res.json using Content-Type: application/json which tells the client that the string that he got is actually a json object, so no need for you to use JSON.parse.
You can see the Content-Type under the response headers property.

API endpoint returns text before and after the JSON content, causing parsing error

I'm using postman to test calling a rest service endpoint.
I'm trying to parse the JSON return content but it throws an error because the response body has more than just JSON.
This is how I parse it in my postman test script:
var jsonData = JSON.parse(responseBody);
Here is the response body:
--13398550-b6ea-4731-a8ee-4b2ad24c3cfe
Content-Type: application/json; charset=utf-8
//this is the actual content I want to parse --->
{"id":"123456","value":"the_value"}
--13398550-b6ea-4731-a8ee-4b2ad24c3cfe--
When I try to parse it, I get the following error (in postman)
There was an error in evaluating the test script: SyntaxError:
Unexpected number in JSON at position 3
Obviously because the content being parsed is not just JSON
Is this something special that the api is doing? Or am I just parsing it incorrectly?
NOTE: I'm not including details of the rest service function. If the cause of this issue is something that is being done by the service itself, then that is enough of an answer for me to perhaps ask another question or do some further investigation. The purpose of this question is to ask whether this is something special being done in HTTP, or if it's the service.
Edit:
I managed to see the server side code and it is indeed manually building the response with boundaries identified by a GUID. I'll have to manually parse the response
The server is not emitting straight up application/json, it's packed in a multipart mime envelope.
Whether or not it's doing that correctly depends on the response headers. If you didn't expect a multipart response, but a simple JSON response, then I'd say yes: it's something you need to fix server-side.