Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Modify Default JSON response

I have a REST controller that returns a list of products like so:

Current output

[  
   {  
      "id":1,
      "name":"Money market"
   },
   {  
      "id":2,
      "name":"Certificate of Deposit"
   },
   {  
      "id":3,
      "name":"Personal Savings"
   }
]

In order to get things working with our JS grid library, I need the modify the response to look like:

Desired output

{ "data" :
   [  
       {  
          "id":1,
          "name":"Money market"
       },
       {  
          "id":2,
          "name":"Certificate of Deposit"
       },
       {  
          "id":3,
          "name":"Personal Savings"
       }
    ]
}

Controller

@RequestMapping(value = "/api/products", method = RequestMethod.GET)
public ResponseEntity<?> getAllProducts() {

  List<Product> result = productService.findAll();
  return ResponseEntity.ok(result);
}

Is there an easy way to modify the JSON response using native Spring libraries?

like image 401
A_B Avatar asked Mar 16 '17 18:03

A_B


2 Answers

You can put result object into a Map with key "data" and value as result.

map.put("data", result);

Then return the map object from the rest method.

return ResponseEntity.ok(map);

like image 157
notionquest Avatar answered Sep 30 '22 19:09

notionquest


Using org.json library:

JSONObject json = new JSONObject();
json.put("data", result);

The put methods add or replace values in an object.

like image 45
Muhammad Saqlain Avatar answered Sep 30 '22 19:09

Muhammad Saqlain