Home > Back-end >  How to create a costum JSON response in Spring Java?
How to create a costum JSON response in Spring Java?

Time:02-11

Currently, I am trying to return a costum created response from my REST API. My goal is to create the following response.

{
   "status": "Success",
   "message": "More details here",
   "data": {
      "records": [
         {
            "record": "Lorem ipsum",
            "code": 0,
            "errors": null
         },
         {
            "record": "Lorem ipsum",
            "code": 1,
            "errors": [
               "First error",
               "Second error"
            ]
         }
      ]
   }
}

My API endpoint looks like the following.

@PostMapping(value="/my-url", 
   consumes=MediaType.APPLICATION_JSON_VALUE, 
   produces=MediaType.APPLICATION_JSON_VALUE)
public Response check_records(@RequestBody(required=true) Records records) {
   // Do Stuff
}

The 'Response' class:

public class Response {
   private String status;
   private String message;
   private Map<String, List<RecordResponse>> data;
   
   // Default getter / setter
}

The 'RecordResponse' class:

public class RecordResponse {
   private String record;
   private Integer code;
   private String[] errors;

The response itself is returning anything but JSON. Neither way it is returning an error or returns the object reference in the json:

{
   "status": "Success",
   "message": "More details here",
   "data": {com.example.restservice.data@2071af5d}
}

CodePudding user response:

You can use generics to have a decent typecontroll for your response wrapper

public class Response<T> {
   private String status;
   private String message;
   private T data;

   //all args contructor
}

and

public class Records{
  List<RecordResponse> records;
}

public class RecordResponse {
   private String record;
   private Integer code;
   private String[] errors;



public Response<Records> check_records(@RequestBody(required=true) Records records) {
    RecordResponse recordResponses=//build responses 
    Records records=//build records
    return new Response<Records>(status,message,records);
}

This should produce response close if not exact as you have requested

  • Related