简体   繁体   中英

Spring Boot REST display id of parent only in a JSON response

Assume I have the following class:

public class ChildEntity {

   ...

   @ManyToOne
   private ParentEntity parent;  

   ...

}

Now, I have a REST endpoint that retrieves a child entity object from the database, thus my JSON is the following:

{"id": "123", "name":"someName", "parent": { //parent fields here } ... }

I want to format my JSON responses in another way. I want parent display only the id from the database, instead of the whole object:

{"id": "123", "name":"someName", "parentId": "1" ... }

Basically returning entities directly from endpoints isn't a good idea. You make very tight coupling between DB model and responses. Instead, implement a POJO class that will be equivalent of the HTTP response you sent.

This POJO will have all ChildEntity fields and parentId only and will be constructed in HTTP layer.

Please, see the discussion in comments, basically such an object returned from web layer is not a DTO according to me.

I am annotating @JsonIgnore which ever field I do not want to be part of JSON response. Creating parallel POJO for each entity is costly affair.

@JsonIgnore
@NotNull
@Column(name="DELETED")
private boolean deleted = false;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM