3

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?

Arghavan
  • 1,131
  • 1
  • 9
  • 15
Jan
  • 335
  • 3
  • 14

1 Answers1

0

I believe your options are:

  • @JsonIgnore on the fields you don't want serialized in A.
  • Configure the Jackson ObjectMapper to only serialize annotated fields and then annotate the fields you do want serialized in B with @JsonProperty.
  • Copy the A instances returned from getAllRelevantAsAsList() into a new object type which doesn't have the fields (either an anonymous implementation of B which delegates to a, or create a new child class that extends B but doesn't have new fields and has a copy ctor for an A instance.

    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());
    
Matthew Madson
  • 1,413
  • 12
  • 23