Hello everybody,
maybe some of you guys can use it.
private Tree createTree() {
Tree tree = new Tree();
tree.setSizeFull();
tree.setContainerDataSource(getHierachicalContainer(getJSONArrayAsString()));
tree.setItemCaptionMode(ItemCaptionMode.PROPERTY);
tree.setItemCaptionPropertyId("value");
return tree;
}
private HierarchicalContainer getHierachicalContainer(String JSONArrayAsString) {
HierarchicalContainer container = new HierarchicalContainer();
container.addContainerProperty("value", String.class, "");
Object newRootId = container.addItem();
container.getItem(newRootId).getItemProperty("value").setValue("Root");
buildStructure(container, newRootId, JSONArrayAsString);
return container;
}
private void buildStructure(HierarchicalContainer container, Object rootId, String leaveValue) {
try {
// isJSONObject
JSONObject jsonObject = new JSONObject(leaveValue);
Iterator<?> jsonObjectIter = jsonObject.keys();
while (jsonObjectIter.hasNext()) {
String key = jsonObjectIter.next().toString();
createNode(container, rootId, String.valueOf(key.toString()), jsonObject.get(key).toString(), true);
}
} catch (JSONException e) {
try {
// isJSONArray
JSONArray jsonArray = new JSONArray(leaveValue);
for (int i = 0; i < jsonArray.length(); i++)
createNode(container, rootId, String.valueOf(i), jsonArray.get(i).toString(), true);
} catch (JSONException e1) {
// isValue
createNode(container, rootId, leaveValue.toString(), null, false);
}
}
}
private void createNode(HierarchicalContainer container, Object rootId, String nodeValue, String leaveValue, Boolean childrenAllowed) {
Object newRootId = container.addItem();
container.getItem(newRootId).getItemProperty("value").setValue(nodeValue);
container.setChildrenAllowed(newRootId, childrenAllowed);
container.setParent(newRootId, rootId);
if (leaveValue != null)
buildStructure(container, newRootId, leaveValue);
}
private String getJSONArrayAsString() {
String jsonArrayAsString = "[{\"value1\":1337, \"nestedJSONObject1\": {\"value1\":\"abcd\"}, \"nestedJSONArray1\":[{\"ArrayValue\":1},{\"ArrayValue\":2}]
},{\"value2\":1337, \"nestedJSONObject2\": {\"value2\":\"abcd\"}, \"nestedJSONArray2\":[{\"ArrayValue\":1},{\"ArrayValue\":2}]
}]";
return jsonArrayAsString;
}
Regards,
Michael