I got the following response from the API call :
[{"id":63,"name":"Apple Inc.","ticker":"AAPL","website":"www.apple.com","street1":null,"street2":null,"country":null,"postal_code":null,"city":null,"state":null,"type_value":"PUBLIC","person":[{"id":6854208},{"id":6854192},{"id":7795},{"id":6837866},{"id":6854188},{"id":6840774},{"id":6838278},{"id":7637},{"id":6839671},{"id":6837862},{"id":6840759},{"id":6840766},{"id":6838242},{"id":6840830},{"id":6840838},{"id":7875},{"id":3038662},{"id":865765},{"id":6839669},{"id":6837834},{"id":6839685},{"id":6839931},{"id":6840777},{"id":6838232},{"id":6838260},{"id":1859904},{"id":6854204},{"id":6838238},{"id":6839751}],"type":3001,"revenue":null,"industry":[{"industry":"Computer Hardware","industry_id":5009},{"industry":"Electronics","industry_id":5016},{"industry":"Technology - All","industry_id":5044}],"description":null}]
How do I get the value of name from the response?
This is what I have right now:
System.err.println("fullBspApiUrl"+fullBspApiUrl);
Response resp = get(fullBspApiUrl);
System.err.println("This is response"+resp);
String bJson = resp.asString();
System.err.println("This is response after string conversion"+bJson);
JsonPath jsonpath = new JsonPath(bJson);
System.err.println("Instantiate JsonPath "+jsonpath);
//String bspOrgName = jsonpath.getString("organizationName[0]");
String bspOrgName = jsonpath.getString("organizationName[0]");
System.err.println("This is response after JsonPath string conversion "+bspOrgName);
assertEquals(resp.getStatusCode(),200);
assertEquals(bspOrgName,"Apple Inc");
It returns Null instead of Apple.
get(fullBspApiUrl).then().statusCode(200).
and().assertThat().body(name[0], equalTo("Apple Inc"))
name[0] works fine. The previous response had it as OrganizationName
Related
I am getting response with okhttp library android java from a url and i converted that response to string.below is response string :
Here is the response string :
"{\"data\":{\"refrenceCode\":\"upfF+kMKv4Q=\",\"identityTypeId\":\"NV25GlPuOnQ=\",\"idNumber\":\"1000\",\"dateOfBirth\":19961004,\"registrationDate\":\"2020-05-12T12:03:47.647\",\"mobile\":\"0022343 \",\"regionId\":\"NV25GlPuOnQ=\",\"cityId\":\"NV25GlPuOnQ=\",\"carTypeId\":\"NV25GlPuOnQ=\",\"carNumber\":\"aa 000\"},\"status\":true,\"errorCodes\":[]}"
and when i tried to convert that string to json objectwith below method;
JSONObject jsonobj = new JSONObject(responsestring);
I got following json exception :
org.json.JSONException: Value {"data":{"refrenceCode":"upfF+kMKv4Q=","identityTypeId":"NV25GlPuOnQ=","idNumber":"1000","dateOfBirth":19961004,"registrationDate":"2020-05-12T12:03:47.647","mobile":"0022343 ","regionId":"NV25GlPuOnQ=","cityId":"NV25GlPuOnQ=","carTypeId":"NV25GlPuOnQ=","carNumber":"aa 000"},"status":true,"errorCodes":[]} of type java.lang.String cannot be converted to JSONObject
How it can be fixed?
Here is a solution based on the collective work in the comments:
responsestring = responsestring.substring(1, responsestring.length - 1).replace("\\\"", "\"");
Thanks for #chrylis-onstrike- observation, it helped.
I fixed it by removing first and last " and then replacing \ like below
responsestring = responsestring.replace("\","");
following is my post re quest , in console i am able to see the log i want to store in variable.:
RestAssured.baseURI = "https://www.dummy.com//services";
RestAssured.given().
headers("data",crypto).
when().
post("//auth.svc/auth").
then().contentType(ContentType.JSON).log().all();
Response response = RestAssured.given().
headers("data",crypto).
when().
post("//auth.svc/auth").
then().contentType(ContentType.JSON).
extract().response();
Afterwards you could save the response as a string with response.asString() or inspect the json with a JsonPath object. For example:
JsonPath jsonPathEvaluator = response.jsonPath();
jsonPathEvaluator.get("xyz");
Here is my code that works:
Response response = target.queryParam("start", startIndex)
.queryParam("end", end)
.request()
.accept(MediaType.APPLICATION_XML)
.header(authorizationHeaderName, authorizationHeaderValue)
.get();
MyClass message = response.readEntity(MyClass.class);
I want to also be able to do this:
if(loggingTurnedOn == true)
{
logger.debug(XMLfromResponseMessage);
}
But I don't know how to get the raw XML String from the Response.
An answer from another question:
You can use Response#bufferEntity(), which will allow you to read the entity stream multiple times.
Response response = ...
response.bufferEntity();
String s = response.readEntity(String.class);
MyEntity me = response.readEntity(MyEntity.class);
response.close();
I am working on a project in which I am making a rest url call to my servers which gives me back a JSON String as a response. If there are any problems with the service then it will give me either of these below JSON String as the response -
{"error":"no user_id passed"}
or
{"warning": "user_id not found", "user_id": some_user_id}
or
{"error": "user_id for wrong partition", "user_id": some_user_id, "partition": some_partition}
or
{"error":"no client_id passed"}
or
{"error": "missing client id", "client_id":2000}
Below is my code by which I am making a call and here response variable will have above JSON string if something has gone wrong on the service side but if it is a success response, then it won't contain any of the above JSON String. It will be a valid JSON String with a proper data but JSON String for success response is totally different as compared to above error case JSON String so I cannot have a same POJO for that..
RestTemplate restTemplate = new RestTemplate();
String response = restTemplate.getForObject(url, String.class);
// check response here as it will have above error JSON String if
// something has gone wrong on the server side, and some other data if it is a success
And I need to log an error if response contains any of the above JSON String as it's an error but if it doesn't contain the above JSON String, then log as a success..
NOTE: If the response from the service is not success, then it will have error and warning as the first key in the JSON String.. But if it is a success, then it will proper data in the JSON String..
What is the easiest and efficient way to solve this problem?
This works if you return different response when it is successful and it doesn't include key "error".
JSONObject jsonObject = new JSONObject(response);
bool isError = false;
//I checke for one error you can do same for other errors and warning as well. You can directly check this from array.
if(jsonObject.has("error"))
{
String error = jsonObject.getString("error");
if(errror == "no user_id passed")
{
isError = true;
}
}
if(!isError)
{
//continue what you were doing.
}
You can use "has" method of JSONObject from org.json library to check if a particular key is present in your json string. You can use this method to check if error is returned by your server and process accordingly.
Example code:
//Array of all errors
String[] error_list = ["no user_id passed","user_id not found","user_id for wrong partition","no client_id passed"];
public boolean isErrorResp(String json_response)
{
try
{
JSONObject json_obj = new JSONObject(json_response); //create JSONObject for your response
//check if your response has "error" key if so check if the value of error key is in the error_list array
if(json_obj.has("error")&&Arrays.asList(error_list).contains(json_obj.getString("error")))
{
return true;
}
else if(json_obj.has("warning")&&Arrays.asList(error_list).contains(json_obj.getString("warning")))
{
return true;
};
return false;
}
catch(JSONException ex)
{
//error handling for improper json string.
return false;
}
}
Hope this helps.
Am using jsonobject and json array and converting the final result to string using jsonobject.toString() function and returning the string to browser.
Code snippet:
JSONArray VMs= new JSONArray();
JSONObject resultSet = new JSONObject();
for(Vector<String> stages : mrs)
{
VMs.put(new JSONObject().put("Vm",stages.get(0)));
}
resultSet.append("ServerDetails",(new JSONObject().put("Server",sName).append("Vms", stageNames)));
return resultSet.toString();
output on browser:
"{\"ServerDetails\":[{\"Server\":\"myserver45\",\"Vms\":[[{\"Vm\":\"vm1022\"},{\"Vm\":\"vm9875\"}]]}]}"
I don't want it to return this way. How do i make this return as follows without slashes-
"{"ServerDetails":[{"Server":"myserver45","Vms":[[{"Vm":"vm1022"},{"Vm":"vm9875"}]]}]}"
I don't understand why " gets replaced with \" everywhere. Please help.
If you are using net.sf.json json library, both jsonObject and jsonObject.toString() provide output values without string escape character. Which library you are using..?
Also try returning the original jsonObject itself than the one converted with toString. It might give you the desired result.
Alternate option would be to unescape the string which is send to browser. You can use stringescapeutils from org.apache.commons.lang for this return StringEscapeUtils.unescapeJava(resultSet.toString()) ;