简体   繁体   中英

Convert tree data structure from Database into JSON in Java

We have a database that has the child_id, parent_id and the other details for each row of a tree in the database. I am looking for a best method to read the data from the database recursively and create the JSON not knowing how deep the child items run under each root node. Also is there something that helps create the JSON without having to write the syntax of JSON manually in the program? Thanks in advance for any pointers.

I do not think that you can find tool that can help you to read your application level data from your database and create your tree-like data structure. So, this is what you have to implement yourself.

I'd recommend you to read the entities one-by-one and arrange them into tree during reading.

The second part is simpler. There are several Java-to-JSON tools. For example GSON form Google. Take a look here: http://code.google.com/p/google-gson/ A couple of lines of code and your tree is serialized into JSON.

BTW be careful: it supports trees but according to my experience does not support graphs with loops.

Read your from the Database and create a Tree object. You can pretty easily use something like this:

public class Node<T> {
    public T content;
    public List<Node<T>> children;
}

Once you've built that tree, you can send that object to a JSON serializer like Flexjson to convert that Java object to JSON. Flexjson has the added benefit that if you have loops in the graph like children knowing about their parent node then it won't fail to serialize as other libraries will.

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