Reputation: 136
I have checked the @JsonIdentityInfo
, the @JsonManagedReference
, and the @JsonBakcReference
, but it seems none of them manages my issue.
Basically I have the following table:
id | name | parent_id
1000 | Item 1 | (null)
2000 | Item 2 | 1000
2001 | Item 3 | 2000
2002 | Item 4 | 2000
3000 | Item 5 | 1000
3001 | Item 6 | 3000
I have the following JPA entity:
@Entity
@Table(name = "table")
public class table {
@Id
@Column(name="id")
private Long id;
@Column(name="name")
private String name;
@Column(name="parent_id")
private Long id;
//getters setters
}
What I want to achieve is to produce a JSON string that is the following:
[{title: "Item 1", key: "1000"}, {title: "Item 2", key: "2000", children[{title: "Item 3", key:"2001"},{title: "Item 4", key": "2002"}]},{title: "Item 5", key:"3000", children[{title: "Item 6", key: "3001"}]}]
My main problem is how do I write the serialization to JSON? knowing that I can have several levels in each other
Upvotes: 1
Views: 766
Reputation: 89
Even I am looking for one answer - I have many methodologies, but not sure which one is the best fit. In most of my projects, I have done a custom mapping
My Entity class will have two methods - fromJSON to deserialize the JsonNode/JSONObject to my bean and toJSON() method to serialize the entity data to JsonGenerator/JSONObject depending on the library I am using.
I found another alternative to above (1) : I used Jackson-databinding to serialize/deserialize the data to JSON. If you have spring and mvc dependency and jackson databinding library in the classpath this will be done automatically. This looks promising.
But with (1) above I can customize the format and tag names in the generated JSON output. Also I can export single Constants file for TAG names which can be used in client project as well (this helps me a lot as I use GWT for client UI development).
Upvotes: 1