0

This is my 1st project in java spring. So i m trying to figure out the best way to do things.

I have several Rest Apis in my project for which different kinds of API response will be sent.

Somewhere i m getting data in List Format, somewhere else another format. So i m trying to figure out the best way to send response in JSON format.

One of the API Response i have is this:

{
"result": "true",
"message": null,
"data": "{\"id\":1,\"firstName\":\"test\",\"lastName\":\"test\",\"emailId\":\"[email protected]\",\"mobileNo\":\"1234567890\",\"alternateMobileNo\":\"1234567890\",\"username\":\"test\",\"password\":\"7c4a8d09ca3762af61e59520943dc26494f8941b\",\"status\":\"active\",\"userRole\":\"test\",\"dateCreated\":\"Feb 6, 2019\",\"permissions\":\"\"}"
}

My biggest issue is the formatting of data key in the above JSON.

This is my controller action:

@RequestMapping(value = "/admin/staff/get", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public Map get(HttpServletRequest request, @RequestParam Map<String, String> parameters) {
 Map<String, String> response = new HashMap<>();
 Gson gson = new Gson();
 Staff staff = new Staff();
 staff.setId(new Integer(parameters.get("id")));
 List validateToken = loginAuthTokenService.validateToken(new Integer(request.getHeader("loginId")), request.getHeader("loginType"), request.getHeader("token"));
 if (validateToken.size() > 0) {
 Staff staffDetails = staffService.getStaff(staff.getId());
 response.put("result", "true");
 response.put("data", gson.toJson(staffDetails));
 } else {
 response.put("result", "false");
 response.put("message", "No records found.");
 }
 return response;
}

Should I create a separate Class for sending API Response or anyone please guide me the proper way of sending response.

Thanks

asked Apr 5, 2019 at 6:35

2 Answers 2

1

Gson#toJson(Object) returns a String and that String is mapped as JSON key in your map.

You don't have to convert your object to a JSON, Spring will do it for you (it uses Jackson as JSON mapper so you don't have add Gson dependency to your project.

A simple and working implementation could be something like:

@RequestMapping(value = "/admin/staff/get", method = RequestMethod.POST, consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
public ResponseEntity<?> get(
 @RequestParam("id") Integer id,
 @RequestHeader("loginId") Integer loginId,
 @RequestHeader("loginType") String loginType, 
 @RequestHeader("token") String token) {
 List validateToken = loginAuthTokenService.validateToken(loginId, loginType, token);
 if (!validateToken.isEmpty()) {
 Stuff stuff = staffService.getStaff(id);
 return ResponseEntity.ok(stuff);
 }
 return ResponseEntity.notFound().body("No records found.");
}

Also consider to not return a generic map from your method, but the Stuff object your front-end needs. In case of failure you should return a failure object with a specific http response code (e.g. 404, 400, 500...).

Take a look at this guide.

answered Apr 5, 2019 at 6:43
Sign up to request clarification or add additional context in comments.

6 Comments

If i will do this, how will i send response.put("result", "true"); since "true" is not an object?
"true" is a String, a String is an Object. By the way, take a look at my last edit to the answer.
I see, but @ResponseStatus(value = HttpStatus.OK) i will have to use above the function, how do i send different kinds of response based on data available or not like i did true/false ?
Either by returning a ResponseEntity with proper http code or throwing an exception in your method and using a ControllerAdvise to handle it like the linked guide says (there plenty of guides, I just linked you the first I found in Google)
Here, this article may be better
|
0

To format the the data attribute , you can store it in a map :-

Map<String, Object> map1= new HashMap<String, Object>();

and is you have multiple data attributes you can create an ArrayList of Maps :-

ArrayList<Map<String, Object>> dataClerk = new ArrayList<Map<String,Object>>();

I had a similar usecas so i used the below code :-

obj = parser.parse(response);
JSONObject jobj = (JSONObject)parser.parse(response); 
JSONArray jsonarr_1 = (JSONArray) jobj.get(item);
for(int i=0 ;i<jsonarr_1.size();i++) {
 Map<String, Object> entry = new HashMap<String, Object>();
 org.json.simple.JSONObject temp= (org.json.simple.JSONObject) 
 jsonarr_1.get(i);
 Set<String> attributes= temp.keySet();
 for(String s: attributes) {
 entry.put(s, temp.get(s));
 }
 }
answered Apr 5, 2019 at 6:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.