Estoy tratando de mostrar un archivo JSON en un TreeView utilizando JavaFX y SceneBuilder. Me seguido este tutorial https://www.geeksforgeeks.org/parse-json-java/ para leer el archivo JSON, pero tengo problemas analizarlo.
Traté de analizar el archivo JSON (archivo que he subido mediante un botón en la interfaz) utilizando el sencillo JSON biblioteca y emitir el JSONObjects a las cadenas, pero no sé cómo agregar esas cadenas en el TreeView. En primer lugar he tratado de convertir una cadena a un TreeItem, pero no funciona en absoluto.
Yo diría que el archivo JSON que estoy tratando de análisis sintáctico tiene una estructura complicada, y me parece un poco difícil de analizar que de la misma manera que estoy haciendo ahora.
Una estructura simplificada del archivo de mi JSON:
{
"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
}
]
}
}
El análisis de JSON método empecé a escribir:
@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);
}
En resúmen: Cómo añadir un JSONObject / cadena a una TreeView using JavaFx and JSON_simple library?
Esta es una pregunta adicional, que no necesito necesaria una respuesta: Es Hay algún método más simple para escribir el código? ¿Que recomiendas?
Este método va a construir una forma recursiva TreeItem
utilizando un org.json.simple
elemento:
@SuppressWarnings("unchecked")
private static TreeItem<String> parseJSON(String name, Object json) {
TreeItem<String> item = new TreeItem<>();
if (json instanceof JSONObject) {
item.setValue(name);
JSONObject object = (JSONObject) json;
((Set<Map.Entry>) object.entrySet()).forEach(entry -> {
String childName = (String) entry.getKey();
Object childJson = entry.getValue();
TreeItem<String> child = parseJSON(childName, childJson);
item.getChildren().add(child);
});
} else if (json instanceof JSONArray) {
item.setValue(name);
JSONArray array = (JSONArray) json;
for (int i = 0; i < array.size(); i++) {
String childName = String.valueOf(i);
Object childJson = array.get(i);
TreeItem<String> child = parseJSON(childName, childJson);
item.getChildren().add(child);
}
} else {
item.setValue(name + " : " + json);
}
return item;
}
Análisis de un archivo:
JSONParser parser = new JSONParser();
JSONObject root = (JSONObject) parser.parse(new FileReader(new File("json_file_path")));
TreeView<String> treeView = new TreeView<>();
treeView.setRoot(parseJSON("root_object", root));