How to get pretty formatted ResponseEntity for Custom Response Model? - json

When I am returning String for ResponseEntity it shows pretty formatted json in Postman but when I am returning CustomModel for ResponseEntity, it shows non formatted json.
Code 1:
#PostMapping("/json1")
ResponseEntity<String> getData1() {
String result = "{\"name\":\"Alex\"}";
return ResponseEntity.ok().body(result);
}
Postman output 1:
{
"name": "Alex"
}
Code 2:
class RestResp {
public ResponseEntity<?> data = null;
}
#PostMapping("/json2")
ResponseEntity<RestResp> getData2() {
String result = "{\"name\":\"Alex\"}";
RestResp response = new RestResp();
response.data = ResponseEntity.ok().body(result);
return ResponseEntity.ok().body(response);
}
Postman output 2:
{
"data": {
"headers": {},
"body": "{\"name\":\"Alex\"}",
"statusCode": "OK",
"statusCodeValue": 200
}
}
Why am I getting "{\"name\":\"Alex\"}" non formatted? How can I get the properly formatted json in Postman?

You can do it in many ways.
With dedicated object:
class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
and
RestResp response = new RestResp();
response.data = ResponseEntity.ok().body(new Person("Alex"));
return ResponseEntity.ok().body(response);
Map it to json:
String result = "{\"name\":\"Alex\"}";
ObjectMapper mapper = new ObjectMapper();
JsonNode node = mapper.readTree(result);
RestResp response = new RestResp();
response.data = ResponseEntity.ok().body(node);
return ResponseEntity.ok().body(response);
Or just use a map:
Map<String,Object> map = new HashMap<>();
map.put("name", "Alex");
RestResp response = new RestResp();
response.data = ResponseEntity.ok().body(map);
return ResponseEntity.ok().body(response);

Related

How to parse JSON in rest assured stepdefination class?

Below is the JSON request body:
{
"memberId":"21bda54e-895a-4528-8788-698fce5b5",
"prodList":[
{
"productCode":"312"
}
]
}
Below is the code which I have written. Let me know How to parse the above JSON payload in the rest assured step definition file.
public class Generate_Bill {
private Response response;
private String accessToken;
private void jsonBodyUsingMap(String string, List singletonList) {
// TODO Auto-generated method stub
}
public String generateStringFromResource(String path) throws Throwable {
return new String(Files.readAllBytes(Paths.get(path)));
}
#Given("Post Generate Bill API")
public void post_Generate_Bill_API() {
RestAssured.baseURI = Initialization.url;
}
#When("call the Post Generate Bill API with valid token and details")
public void call_the_Post_Generate_Bill_API_with_valid_token_and_details() throws Throwable {
accessToken = TokenGeneration.accessToken;
String jsonBody = generateStringFromResource("src/test/java/request/Generate_Bill.json");
//Gson gson = new Gson();
//JsonObject inputObj = gson.fromJson(jsonBody, JsonObject.class);
Map<String, Object> jsonBodyUsingMap = new HashMap<String, Object>();
// singletonList() to return an immutable list containing only the specified object
jsonBodyUsingMap("prodList", Collections.singletonList(new HashMap<String, Object>() {
{
put("productCode", "31");
}}
));
jsonBodyUsingMap.put("memberId", "21bda54e-895a-4528-8788-6985f6fce5b5");
response = RestAssured.given()
.header("Content-Type", "application/json")
.header("Authorization", "Bearer " + accessToken)
.when()
.post(Initialization.Generate_Bill);
}
#Then("validate Generate Bill API for {int} status code")
public void validate_Generate_Bill_API_for_status_code(Integer int1) {
int status_code = response.getStatusCode();
System.out.println("status is: " +status_code);
Assert.assertEquals(200, status_code);
}
}

Get Access token genertaed from JSON in SpringBoot Application

#RequestMapping(value = "/check", method = RequestMethod.GET)
public ResponseEntity<Product> createProducts() throws JsonProcessingException {
String reqUrl = "http://localhost:8080/home";
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> bodyParamMap = new HashMap<String, String>();
bodyParamMap.put("grant_type", "K1");
bodyParamMap.put("client_id", "K2");
bodyParamMap.put("client_secret", "sjxjkdcnjkk");
String reqBodyData = new ObjectMapper().writeValueAsString(bodyParamMap);
HttpEntity<String> requestEnty = new HttpEntity<>(reqBodyData, headers);
ResponseEntity<Product> result = restTemplate.postForEntity(reqUrl, requestEnty, Product.class);
return result;
}
I am geeting a JSON response form result which have access_token which I want to get.
I tried using JSONObject but it is not working. How Can I fetch the value of access_token
JSONObject jsonObject = JSONObject.fromObject(result.toString());
String m = jsonObject.get("access_token").toString();
I tried using this but it is showing compile time error
My output is accepted as
{"access_token":"ghdjhdjhhh","expires_in":2300}
I want to fetch this access_token
when you use postForEntity your Product.class is suppose to represent your result (responseType), so if your converters are well defined(normally the spring boot default ones are sufficient for json) with your class Product looking like this
public class Product {
#JsonProperty("access_token")
private String accessToken;
#JsonProperty("expires_in")
private Long expiresIn;
public String getAccessToken() {
return accessToken;
}
public Long getExpiresIn() {
return expiresIn;
}
public void setAccessToken(String accessToken) {
this.accessToken = accessToken;
}
public void setExpiresIn(Long expiresIn) {
this.expiresIn = expiresIn;
}
}
then you can get your result like this
ResponseEntity<Product> result = restTemplate.postForEntity(reqUrl, requestEnty, Product.class);
Product product = result.getBody();
String token = product.getAccessToken()

Spring API should return JSON instead of escaped String

I have Spring endpoint which is supposed to return JSON so it can be collapsed/expanded via Chrome. Is there a way to tell Spring that string in message is actual Json representation, and no need to escape double quotes
Endpoint declaration:
#GET
#Path("/validate/{id}")
#Produces("application/json")
Response validate(#Context HttpServletRequest request, #PathParam("id") String id);
Endpoint implementation:
public Response validate(HttpServletRequest request, String id) {
try {
return validatorService.validate(request, String id);
} catch(Exception e) {
throw new MyCustomException(e);
}
}
Exception Handler:
public class ExceptionHandler implements ExceptionMapper {
#Override
public Response toResponse(MyCustomException exception) {
String json = buildJsonResponse(exception);
Message message = new Message(json);
return Response.status(ERROR_HTTP_STATUS_CODE).entity(response).build();
}
}
public class Message {
String json;
public Message(String json) {
this.json = json;
}
public String getJson() {
return json;
}
}
Response:
"json": "{ \"key\": \"value\" }"
Expected response:
"json": { "key": "value" }
Solution:
private JsonNode convertToJson(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readTree(json);
} catch (IOException e) {
return NullNode.getInstance();
}
}
Why don't you annotate your getter with #JsonRawValue
public class Message {
String json;
public Message(String json) {
this.json = json;
}
#JsonRawValue
public String getJson() {
return json;
}
}
That
You are converting your object to string in json format. Spring just returns a string value in json parameter. If you want to return json formated object not string do not convert your object to string( json ). Convert your json to Object type and delete the line below.
String json = buildJsonResponse(exception);
If you want to return custom json in string parameter convert your all object to json not only its variable.
You can just return string from your rest api with produces parameter like you added.
produces = "application/json"

When i'm using volley in android studio how to get response and iterate over Json ? if it is multi-dimensional array

I can't use JsonObjectRequest instead of StringRequest because I need send it via POST method
After analyzing lot of solutions I posted the question here
My php api output is looks like
[
{
"username": "arun",
"password": "kumar"
},
{
"username": "arun",
"password": "ak"
},
{
"username": "arun",
"password": "mypass"
},
{
"username": "arun",
"password": "TestPW"
}
]
In Android side I am using below code to fetch data from web, in the method
public void onresponse()
I don't know how to get above json response, and also iterate over response to print all data in response
String url = "http://myipaddress/index.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonobject = new JSONObject(response);
String output = "";
for (int i = 0; i < jsonobject.length(); i++) {
// print all usernames and passwords
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
You would need to iterate over the JSONArray and get every element as a JSONObject then get the String properties named "username" and "password" from each of them.
try this:
String url = "http://myipaddress/index.php";
StringRequest request = new StringRequest(Request.Method.POST, url, new response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONArray array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject object = array.getJSONObject(i);
final String username = object.getString("username");
final String password = object.getString("password");
// print the output
Log.d("TAG", "username=" + username + ", password=" + password);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("username", username);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(request);
Ideally you should use class models instead, and deserialize directly into this class.
public class UserLoginInfo {
public String username;
public String password;
}
This will make the object much more easy to use and give you the benefits of type safety and autocomplete.
This is a link from a short google search on how to do it with Google's gson library.
IMO use retrofit.
Happy coding! :)

Google Volley not able to get JSON values from passing parameters

I am trying to pass a parameter which is the userID and then get the response in the form of the JSON.
So if userID=1 then the response would be
[{"carname":"Honda","carmodel":"Civic"}]
and if userID=5then the response would be
[{"carname":"Honda","carmodel":"Civic"},{"carname":"VW","carmodel":"Golf"},{"carname":"Ford","carmodel":"Focus"}]
But for some reason, the parameters are not being passed and if they are then I am unable to retrieve values in JSON
This is my code below:
public void getComments(int userID){
String passURL = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest
(passURL, new Response.Listener<JSONArray>(){
#Override
public void onResponse(JSONArray jsonArray) {
try {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
String carName = jsonObject.getString("carname");
String carModel = jsonObject.getString("carmodel");
UserStore userStore = new UserStore(carName, carModel);
list.add(userStore);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
}
}) {
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
params.put("userID", Integer.toString(userID));
return params;
}
};
requestQueue.add(jsonArrayRequest);
}
I suspect it something to do with the fact that I am trying to get the response from the array after passing a parameter. My php works in Postman
Using mcxiaoke library version 1.0.14 and above
JsonArrayRequest
You need to set the Method as Post in JsonArrayRequest as like below
JsonArrayRequest jsonArrReq = new JsonArrayRequest(Method.POST,
url, null,new Response.Listener<JSONArray>()
{
......
//onResponse
......
}
getParams()
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("user", "Android");
return params;
}