A_B
A_B

Reputation: 1019

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?

Upvotes: 5

Views: 5658

Answers (2)

Muhammad Saqlain
Muhammad Saqlain

Reputation: 2202

Using org.json library:

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

The put methods add or replace values in an object.

Upvotes: 5

notionquest
notionquest

Reputation: 39186

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);

Upvotes: 8

Related Questions