import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.control.TreeItem;
import java.util.Set;
public class JsonTreeUtils {
public static TreeItem<Entity> createNode(final Entity je) {
return new TreeItem<Entity>(je) {
private boolean isLeaf;
// We do the children and leaf testing only once, and then set these
// booleans to false so that we do not check again during this
// run. A more complete implementation may need to handle more
// dynamic file system situations (such as where a folder has files
// added after the TreeView is shown). Again, this is left as an
// exercise for the reader.
private boolean isFirstTimeChildren = true;
private boolean isFirstTimeLeaf = true;
@Override
public boolean isLeaf() {
if (isFirstTimeLeaf) {
isFirstTimeLeaf = false;
Entity e = (Entity) getValue();
isLeaf = e.getJsonElement().isJsonPrimitive();
}
return isLeaf;
}
@Override
public ObservableList<TreeItem<Entity>> getChildren() {
if (isFirstTimeChildren) {
isFirstTimeChildren = false;
// First getChildren() call, so we actually go off and
// determine the children of the File contained in this TreeItem.
super.getChildren().setAll(buildJsonChildren(this));
}
return super.getChildren();
}
private ObservableList<TreeItem<Entity>> buildJsonChildren(TreeItem<Entity> jsonElementTreeItem) {
JsonElement f = jsonElementTreeItem.getValue().getJsonElement();
if (f != null && f.isJsonArray()) {
JsonArray asJsonArray = f.getAsJsonArray();
if (asJsonArray != null) {
ObservableList<TreeItem<Entity>> children = FXCollections.observableArrayList();
for (int i = 0; i < asJsonArray.size(); i++) {
JsonElement subChild = asJsonArray.get(i);
children.add(createNode(new Entity(String.valueOf(i), subChild)));
}
return children;
}
} else if (f != null && f.isJsonObject()) {
ObservableList<TreeItem<Entity>> children = FXCollections.observableArrayList();
JsonObject jo = f.getAsJsonObject();
Set<String> sets = jo.keySet();
for (String key : sets) {
JsonElement jsonElement = jo.get(key);
children.add(createNode(new Entity(key, jsonElement)));
}
return children;
}
return FXCollections.emptyObservableList();
}
};
}