PDA

View Full Version : Is there any java JSON library to generate json tree from HashMap



inagendra
16 Dec 2009, 6:17 AM
Hi,

I have a HashMap<String,Collection<String>> object where key is the parent and collection values are children. Can generate a json from this object to create a TreePanel? Are there any java libraries which can do this? If not HashMap, is there any other way to create tree structure using java?

Thanks,
Nagendra

realjax
16 Dec 2009, 7:14 AM
Yes, there are numerous json libs that can do this for you. Google is your friend.

inagendra
16 Dec 2009, 8:21 AM
Hello realjax,

I know there are many json libraries available like Gson, JSON Lib, Flexjson, jackson etc. But my question is not about json libs, it is specific.

For ex, I need to generate some thing like this in the json file:
[{"text":"Brendon Howe","id":"Brendon Howe","leaf":false,"cls":"folder","checked":false,"children":[{"text":"Lisa Pavey","id":"Lisa Pavey","leaf":true,"cls":"folder","checked":false},{"text":"Maria Maggio","id":"Maria Maggio","leaf":true,"cls":"folder","checked":false}]}]

I was able to achieve this using a class I have created as shown below:

public class TreeNode {
private String text;
private String id;
private boolean leaf;
private String cls;
private boolean checked;
List<TreeNode> children;
}

Note: avoided getters, setters and constructor for clarity.

The question is are there any libraries with built in classes which supports this struture? Or are there any libraries which can take predefined data structures like HashMap<String,Collection<String>> and convert it into the above structure automatically.

If you have any idea let me know or else let others reply.

Thanks,
Nagendra

nlotz
16 Dec 2009, 8:28 AM
http://www.json.org/java/index.html , but I think you would need something like this:



public class TreeNode extends HashMap {
public TreeNode() {
put("text", ... );
put("id", ... );
put("leaf", ... );
put("cls", ... );
put("checked", ... );
put("children", new LinkedList<TreeNode>() { ... } );
}
}

inagendra
16 Dec 2009, 8:33 AM
Hi nlotz,

My Class doesn't extend from HashMap. I can directly convert it into json which would give me a proper json that can be used in a Tree Panel. It is tested using gson, it works fine.

Thanks,
Nagendra

nlotz
16 Dec 2009, 8:44 AM
are there any libraries which can take predefined data structures like HashMap<String,Collection<String>> and convert it into the above structure automatically. I was trying to say that the library I suggested should be able to do so.

realjax
16 Dec 2009, 12:26 PM
Json lib.
Create a pojo, supply with data, convert to json.