I am trying to create an API controller with java and spring boot. I want to return specific objects as JSON from specific API endpoints, nothing special so far. Now I have a child class A and a parent class B. B is abstract and A is not abstract, but A contains more attributes than B. I have to pass the attributes of the superclass from A to the API endpoint, but when I cast the an object to an object of the superclass the JSON code contains always the attributes from A.
Is there another way to prevent this than setting the not relevant parts to null or empty elements?
EDIT:
I have the following Code:
@Entity
public abstract class B {
private String name;
private String description;
/* GETTERS AND SETTERS */
}
@Entity
public class A extends B {
private String moreInformation;
/* GETTERS AND SETTERS */
}
@RestController
@RequestMapping("/api/v1/")
public class ApiController {
@RequestMapping(value = "/Bs", method = RequestMethod.GET)
public ResponseEntity<List<B>> getBs() {
List<A> As = DAO.getAllRelevantAsAsList();
List<B> Bs = new ArrayList<>();
Bs.appendAll(As);
return new ResponseEntity<>(Bs, HttpStatus.OK);
}
/* DIFFERENT API ENDPOINTS */
}
The JSON Code generated by the API Endpoint looks like this:
[
{
"name": "CONTENT",
"description": "CONTENT",
"moreInformation": "CONTENT"
},
...
]
I found a possible solution for this problem by annotating the attributes of class A with @JsonIgnore. But the main question of this thread is not limited to this special implementation: Is it possible to get only the attributes of the parent class A without annotating the subclass?