I have a class Order:
@Data
@Entity
public class Order {
private List<Project> projects;
// more fields
}
I have a two API methods in my controller:
@GetMapping
public ResponseEntity<List<Order>> getOrders() {
return ResponseEntity.ok(orderService.getOrders());
}
@GetMapping("/{id}")
public ResponseEntity<Order> getOrder(@PathVariable long id) {
return ResponseEntity.ok(orderService.getOrder(id));
}
So in this case projects
is always sent via JSON, if its present its just getting serialized, if its not present its getting fetched lazily and then serialized. I could avoid it being serialized by annotating the field with @JsonIgnore
. But the problem is that i want to send it sometimes and sometimes i dont. For example in getOrders()
i dont want the projects
to be serialized. In getOrder(...)
i would want projects
to be serialized. Is there any way to tell during runtime either inside custom code or by an annotation that i want to send it in one specific case and not in another case? The only thing i figured out is that - shortly before serializing - i can initialize projects
with null and annotate the entity with @JsonInclude(JsonInclude.Include.NON_NULL)
. That way it wouldnt be sent and if i want to send it i can just avoid initializing it with null. But obviously i dont want to iterate over each Order
in O(n) just to initialize its projects
with null.