I have created a Spring Boot API with some specific business requirements. For most of my controller methods, I am just returning an object that is being serialized into json (correct me if I am using the wrong terminology).
For example, lets say I have an object Dog with fields name and age. Most of my controller methods will just return a json such as: { “Name”: “Fido”, “Age”: “5” }
However, as a business requirement, sometimes I just need to return an Age value, or even a list of ages such as:
{ “Age”: “5 }
Or
{ “List”: [“5”, “3”, “8”] }
Most of my controller methods have the return type ResponseEntity<Dog>
But what should I do about the 2 situations above ( or similar situations)?
For now, I am just using a BSON document. The return type is ResponseEntity<Document>. In the controller method, I would do something similar to
public ResponseEntity<Document> getAge() { String age = dogService.getDogAge(); Document doc = new Document(); doc.put(“Age”, age); return ResponseEntity.status().body(doc); }
Is there a better way to do this?