How to serialize only the ID of a child with Jackson

后端 未结 3 1980
面向向阳花
面向向阳花 2020-11-27 13:16

Is there a built-in way to only serialize the id of a child when using Jackson (fasterxml.jackson 2.1.1)? We want to send an Order via REST which has a Pe

3条回答
  •  情深已故
    2020-11-27 14:13

    Given for example a simple company with employees structure, in combination with

    @JsonIgnore
    @ManyToOne(cascade = {CascadeType.REFRESH, CascadeType.DETACH})
    @JoinColumn(name = "child_id")
    

    I would suggest to add the following:

    @JsonProperty("child_id") for sending the child_id as property without it you won't get anything on client side, and- @JsonIgnoreProperties It will give the option to copy and paste the Json received from the server and send it back for example to update it. Without it you will get an exception when sending back, Or you will have to remove the child_id property from the received Json.

    public class Company {
    @OneToMany(mappedBy = "company", cascade = CascadeType.ALL)
        private List employees;
    }
    
    @JsonIgnoreProperties(value = {"company_id"},allowGetters = true)
    public class Employee{
        @JsonIgnore
        @ManyToOne(cascade = {CascadeType.REFRESH, CascadeType.DETACH})
        @JoinColumn(name = "company_id")   
        public Company company
    
       @JsonIdentityInfo(generator=ObjectIdGenerators.PropertyGenerator.class, 
         property="id")
       @JsonIdentityReference(alwaysAsId=true) 
       @JsonProperty("company_id")
       }
       public Company getCompany() {
            return company;
        }
    }
    

提交回复
热议问题