I'm trying to display a JSON file in a TreeView using JavaFx and SceneBuilder. I followed this tutorial https://www.geeksforgeeks.org/parse-json-java/ for reading the JSON file, but I have problems parsing it.
I tried to parse the JSON file (file that I uploaded using a button in the interface) using the JSON simple library and cast the JSONObjects to strings, but I don't know how to add those strings in the TreeView. First I tried to cast a String to a TreeItem , but it doesn't work at all.
I would say that the JSON file I am trying to parse has a complicated structure, and I find it a little bit difficult to parse it in the same manner I am doing now.
A simplified structure of the my JSON file:
{
"root": {
"array": [
{
"element1": "text",
"element2": {
"detail1Element2": "text",
"detail2Element2": "text"
},
"element3": {
"detail1Element3": "text",
"detail2Element3": "text"
},
"element4": {
"subElement4-1": {
"arraySubElement4-1": [
{
"detail1SubSubElement4-1": "text",
"detail2SubSUbElement4-1": "text"
},
{
"detail1SubSubElement4-1": "text",
"detail2SubSubElement4-1": "text"
}
]
},
"subElement4-2": {
"arraySubElement4-2": [
{
"detail1SubSubElement4-2": "text",
"detail2SubSubElement4-2": "text",
"detail3SubSubElement4-2": "text",
"detail3SubSubElement4-2": "text"
},
{
"detail1SubSubElement4-2": "text",
"detail2SubSubElement4-2": "text",
"detail3SubSubElement4-2": "text",
"detail3SubSubElement4-2": "text"
}
]
},
"element5": "text",
"element6": "text",
"element7": "text"
}
},
{
//second array element; it has the same structure as the first one
},
{
//another array element; it has the same structure as the first one
}
]
}
}
The parsing JSON method I started to write:
@FXML
void parsingJSON(ActionEvent event) throws FileNotFoundException, IOException, ParseException {
Object obj = new JSONParser().parse(new FileReader(fileJSON));
JSONObject jo = (JSONObject) obj;
JSONObject root = (JSONObject) jo.get("root");
JSONArray array = (JSONArray) root.get("array");
JSONObject arrayElement = null;
Iterator i = array.iterator();
TreeItem<String> rootTreeItem = new TreeItem<String>("Root");
TreeItem<String>[] element1Value = null;
String[] element1ValueS = null;
int iterator = 0;
while (i.hasNext()) {
arrayElement = (JSONObject) i.next();
element1ValueS[iterator] = (String) arrayElement.get("text");
System.out.println(element1ValueS);
iterator++;
}
for (int i1 = 0; i1 < element1ValueS.length; i1++) {
rootTreeItem.getChildren().add((TreeItem<String>) element1ValueS[i]); // here's an error
}
TreeItem<String> dataText = new TreeItem<String>("TEXT");
treeviewJSON.setRoot(rootTreeItem);
}
Long story short: How to add a JSONObject/String to a TreeView using JavaFx and JSON_simple library?
This is an additional question, I don't necessary need an answer: It's there any simpler method to write the code? What do you recommend?