Java only returns superclass attributes
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, so far nothing special. Now I have child class A and parent class B. B is abstract and A is not abstract, but A contains more attributes than B. I need to pass superclass attributes from A to API endpoint, but when I make an object to a superclass object , JSON code always contains attributes from A.
Is there any other way to prevent this than by setting unneeded 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 to 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?
source to share
I believe your options are:
-
@JsonIgnore
to fields that you don't want to serialize to A. - Set up the Jackson ObjectMapper to only serialize annotated fields , then annotate the fields you want to serialize to B with
@JsonProperty
. -
Copy the instances of A returned from
getAllRelevantAsAsList()
to a new object type that has no fields (either an anonymous implementation of B that delegates to a, or creates a new child class that extends B but doesn't have new fields and has a copy of the ctor for instance A ...List<B> Bs = DAO.getAllRelevantAsAsList() .stream() .map(a -> new B() { public String getName() { a.getName(); } public void setName(String name) { a.setName(name); } /** other delegated getters and setters **/ }).collect(Collectors.toList());
source to share