I am working with the ZK framework and want to serialize from DefaultTreeModel to JSON format for the view. My data looks like this:
private TreeModel<TreeNode<TreeDataDTO>> dataTree = new DefaultTreeModel<>(catTreeNodeRoot);
I have tried using Gson as follows:
String jsonString = (new Gson()).toJson(dataTree);
but it cannot convert the child data of dataTree. all child data show null in jsonString.
Depends why the data is showing as null. Have you made sure that your TreeDataDTO can be converted to JSON by your Gson instance?
You may want to use something different from the default config, such as serializing null values, which should give you some visibility on what is actually parsed by GSON. To do so, you can the GsonBuilder class to create a Gson instance with revelant config:
GsonBuilder().serializeNulls().create()
If that’s not what you need, you may want to retrieve the data content of each node by making a tree traversal method using recursion.
pseudo code below, but it should look like:
JSONObject serializeTreeNode(treeNode){ //THIS IS PSEUDOCODE
JSONObject thisNode = new JSONObject;
/*write relevant data from the treeNode such as the value and other things you want here */
List<JSONObject> children = new ArrayList();
for(child: treeNode.getChildren()){
children.add(serializeTreeNode(child))
}
thisNode.put("children", children);
return thisNode;
}