5

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?

2 Answers 2

8

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

Sign up to request clarification or add additional context in comments.

Comments

5

Using org.json library:

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

The put methods add or replace values in an object.

Comments

Your Answer

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.