简体   繁体   中英

Serializing JSON from a single entity with Spring and JPA

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

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

  1. 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.

  2. 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).

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