Как добиться формата древовидной структуры JSON - PullRequest
1 голос
/ 13 сентября 2011

Мое требование конвертировать данные из Excel в древовидную структуру.Поскольку я буду использовать панель дерева EXTJS, мне нужно сохранить объект Java в формате JSON:

Logic
---Propositional Logic
---Predicate Logic
---Modal Logic
-------Stit logic
-------Doxastic logic
---Temporal logic

Я читаю данные из таблицы Excel и использую мультикарту, чтобы связать каждый ключ с несколькими значениями.Мой i / p после сохранения в мульти-карте: [логика => логика высказываний, предикат, модальный, временный] [логика модальности = stit, doxastic]

При поиске на форуме stackoverflow я нашел пример кодавот так: я отправил мультикарту в этой функции.Я попытался использовать его для своей цели и добавил коды gson для тестирования.

public static Set <Tree> transform(Map <String, List<String>> input) {

    // Potential tree roots.  We start with all LHS keys as potential roots,
    // and eliminate them when we see their keys on the RHS.
    Set<String> roots = new HashSet<String>(input.keySet());

    // This map associates keys with the tree nodes that we create for them
    Map<String, Tree> map = new HashMap<String, Tree>();

   Gson gs = new Gson();
   String jsonString = null;

    for (Map.Entry<String, List<String>> entry : input.entrySet()) {
        String key = entry.getKey();
        List<String> childKeys = entry.getValue();
        Tree tree = map.get(key);
        if (tree == null) {
            tree = new Tree(key);
            map.put(key, tree);
        }
        for (String childKey : childKeys) {
           roots.remove(childKey);
            Tree child = map.get(childKey);
            if (child == null) {
                child = new Tree(childKey);
                map.put(childKey, child);
            }
            tree.addChild(child);
            jsonString =gs.toJson(tree);
        }


       System.out.println(jsonString);

    }

    Set<Tree> res = new HashSet<Tree>(roots.size());
    for (String key : roots) {
        res.add(map.get(key));
    }
   return res;
}

У меня также есть класс Tree:

public class Tree{

    private String  key;
    private boolean leaf;
    private List<Tree> children = new ArrayList<Tree>();

    public Tree(String key)
    {
        this.key=key;
        leaf=true;
    }

    public void addChild(Tree child)
    {
        children.add(child);
        leaf=false;
    }

}

o / pi get:

{"key":"Logic","leaf":false,"children":[{"key":"Propositional Logic","leaf":true,"children":[]},{"key":"Predicate Logic","leaf":true,"children":[]},{"key":"Modal Logic","leaf":true,"children":[]},{"key":"Temporal Logic","leaf":true,"children":[]}]}

{"key":"Modal Logic","leaf":false,"children":[{"key":"STIT logic","leaf":true,"children":[]},{"key":"Doxastic Logic","leaf":true,"children":[]}]}

Но я хотел, чтобы o / p было таким:

{"key":"Logic","leaf":false,"children":[{"key":"Propositional Logic","leaf":true,"children":[]},{"key":"Predicate Logic","leaf":true,"children":[]},{"key":"Modal Logic","leaf":true,"children":[{"key":"STIT logic","leaf":true,"children":[]},{"key":"Doxastic Logic","leaf":true,"children":[]},{"key":"Coalition Logic","leaf":true,"children":[]}},{"key":"Temporal Logic","leaf":true,"children":[]}]}

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

Спасибо

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...