single custom deserializer for all objects as their ids or embedded whole objects during POST/PUT

前端 未结 3 1443
广开言路
广开言路 2020-12-19 20:29
@Entity
public Product {
   @Id
   public int id;

   public String name;

   @ManyToOne(cascade = {CascadeType.DETACH} )
   Category category

   @ManyToMany(fetch          


        
3条回答
  •  猫巷女王i
    2020-12-19 21:21

    Another approach is to use @JsonCreator factory method if you can modify your Entity

    private class Product {
        @JsonProperty("category")
        private Category category;
    
        @JsonProperty("secondaryCategories")
        private List secondaryCategories;
    }
    
    
    private class Category {
        @JsonProperty("id")
        private int id;
    
        @JsonCreator
        public static Category factory(int id){
            Category p = new Category();
            p.id = id;
            // or some db call 
            return p;
        }
    }
    

    Or even something like this should also work

    private class Category {
        private int id;
    
        public Category() {}
    
        @JsonCreator
        public Category(int id) {
            this.id = id;
        }
    }
    

提交回复
热议问题