2

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.

user1365990
  • 21
  • 1
  • 3
  • http://stackoverflow.com/questions/338586/a-better-java-json-library and http://stackoverflow.com/questions/1688099/converting-json-to-java and http://stackoverflow.com/search?tab=votes&q=[java]%20%2bjson – assylias Apr 30 '12 at 14:23
  • google... google... (http://www.mkyong.com/tutorials/java-json-tutorials/) – Luca Apr 30 '12 at 14:25

2 Answers2

0

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.

AlexR
  • 114,158
  • 16
  • 130
  • 208
  • That was very helpful. I was thinking that I would have to read data and organize it into the tree structure myself too. Thanks for validating my thought. Is there any specific efficient way to organize the data in the tree structure after reading through several levels of child notes . Also what format should the data be for gson to write the json tree structure? – user1365990 Apr 30 '12 at 14:41
0

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.

chubbsondubs
  • 37,646
  • 24
  • 106
  • 138