A separate custom serializer for all built-in annotated objects, which replaces them with identifiers

I have entities like:

@Entity public Product { @Id public int id; public String name; @ManyToOne(cascade = {CascadeType.DETACH} ) Category category @ManyToMany(cascade = {CascadeType.DETACH} ) Set<Category> secondaryCategories; } 

and

 @Entity public Category { @Id public int id; public String name; @JsonCreator public Category(int id) { this.id = id; } public Category() {} } 

You can annotate either just the Category class, or the Category and secondaryCategories properties with an annotation that will serialize them as their identifiers when they are implemented.

right now I get from the server when I do a GET for the product with id = 1:

 { id: 1, name: "product 1", category: {id: 2, name: "category 2" }, secondaryCategories: [{id: 3, name: "category 3" }, {id: 4, name: "category 4" }, {id: 5, name: "category 5" }] } 

is it possible to return:

 { id: 1, name: "product 1", category: 2, secondaryCategories: [3, 4, 5] } 

@JsonIdentityReference(alwaysAsId = true) Category class using @JsonIdentityReference(alwaysAsId = true) works in general, but also only returns identifiers when I select one or a list of categories. I need an id conversion only when the category is included.

Thank!

+1
java json jackson spring-data serialization
Oct 07 '17 at 12:17
source share
1 answer

You need to use @JsonIdentityReference(alwaysAsId = true) only for the category variable.

eg:.

 @Entity public Product { @Id public int id; public String name; @ManyToOne(cascade = {CascadeType.DETACH} ) @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id", scope=Category.class) @JsonIdentityReference(alwaysAsId = true) Category category; @ManyToMany(cascade = {CascadeType.DETACH} ) Set<Category> secondaryCategories; } 
0
Oct 09 '17 at 5:01
source share



All Articles