Spring Error loading default JSON

I have a REST controller that returns a list of such products:

Current output

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

To get work with our JS grid library, I need to modify the answer so that it looks like this:

Desired Conclusion

{ "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 change the JSON response using the Spring built-in libraries?

+4
source share
2 answers

You can put a result object in a map with key "data" and a value as the result.

map.put("data", result);

Then return the map object from the rest method.

return ResponseEntity.ok(map);

+6
source

org.json . put .

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

Source: https://habr.com/ru/post/1672494/


All Articles