Добавьте JSONObject / String в TreeView, используя JavaFx - PullRequest
2 голосов
/ 31 марта 2020

Я пытаюсь отобразить файл JSON в TreeView, используя JavaFx и SceneBuilder. Я следовал этому уроку https://www.geeksforgeeks.org/parse-json-java/ для чтения файла JSON, но у меня возникли проблемы с его анализом.

Я попытался проанализировать файл JSON (файл, который я загрузил с помощью кнопку в интерфейсе) с использованием библиотеки JSON simple и приведение JSONObjects к строкам, но я не знаю, как добавить эти строки в TreeView. Сначала я попытался привести String к TreeItem, но он вообще не работает.

Я бы сказал, что файл JSON, который я пытаюсь проанализировать, имеет сложную структуру, и я нахожу его немного трудно разобрать это так же, как я делаю сейчас.

Упрощенная структура моего файла 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
        }

      ]
    }
}

Метод синтаксического анализа JSON, который я начал писать:

@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); 
}

Короче говоря: Как добавить JSONObject / String в TreeView using JavaFx and JSON_simple library?

Это дополнительный вопрос, мне не нужен ответ: есть ли более простой способ написания кода? Что вы рекомендуете?

1 Ответ

1 голос
/ 03 апреля 2020

Этот метод будет рекурсивно создавать TreeItem с использованием элемента org.json.simple:

@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;
}

Анализ файла:

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));
...