无法从树中打印JSON对象

时间:2018-02-10 21:05:50

标签: java json tree

我有一个问题,我想从树中打印JSONObjects和JSONArrays。当我想打印孩子时会出现问题。

public class program {

public static void main(String[] args) throws IOException {

    File file = new File("");
    File outputfile = new File("");
    PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(outputfile, true)));

    JSONParser parser = new JSONParser();

    try {

        Object object = parser.parse(new FileReader(file));

        JSONObject jsonObject = (JSONObject) object;

        JSONArray jsonArray = (JSONArray) jsonObject.get("declaration-list");

        try {


            Iterator iterator = jsonArray.iterator();

            while (iterator.hasNext()) {

                JSONObject jo = (JSONObject) iterator.next();
                String variableName = (String) jo.get("declared-variable");
                MyTreeNode<String> root = new MyTreeNode<>(variableName);

                try {


                    long value = (long) jo.get("value");

                    MyTreeNode<Long> child1 = new MyTreeNode(value);

                    System.out.println(root.getData());

                    root.addChild(child1);

                    for (MyTreeNode node : root.getChildren()) {
                        System.out.println(node.getData());
                    }

                } catch (Exception e) {

                    final JSONObject jsonValue = (JSONObject) jo.get("value");

                    final String operator = (String) jsonValue.get("operator");
                    final JSONArray arguments = (JSONArray) jsonValue.get("arguments");

                    if (operator.equals("set")) {

                        MyTreeNode<JSONArray> test1 = new MyTreeNode(arguments);
                        root.addChild(test1);

                        for (MyTreeNode node : root.getChildren()) {
                            System.out.print(root.getData() + " = ");
                            System.out.println(node.getData());
                        }
                    }

                    if (operator.equals("pair")) {

                        MyTreeNode<JSONArray> test2 = new MyTreeNode(arguments);
                        root.addChild(test2);

                        for (MyTreeNode node : root.getChildren()) {
                            System.out.print(root.getData() + " = ");                               

                            System.out.println(node.getData());
                        }

                    }


                }
            }

        } catch (Exception e) {

            System.out.println("Oops for now");
        }

    } catch (FileNotFoundException e) {
        System.out.println("Input file not found");
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ParseException e) {
        System.out.println("File was not parsed");
        e.printStackTrace();
    }
    pw.flush();
    pw.close();

}

}

这只是我一直在使用的标准树实现。

class MyTreeNode<T> {
private T data = null;
private List<MyTreeNode> children = new ArrayList<>();
private MyTreeNode parent = null;

public MyTreeNode(T data) {
    this.data = data;
}

public void addChild(MyTreeNode child) {
    child.setParent(this);
    this.children.add(child);
}

public void addChild(T data) {
    MyTreeNode<T> newChild = new MyTreeNode<>(data);
    newChild.setParent(this);
    children.add(newChild);
}

public void addChildren(List<MyTreeNode> children) {
    for (MyTreeNode t : children) {
        t.setParent(this);
    }
    this.children.addAll(children);
}

public List<MyTreeNode> getChildren() {
    return children;
}

public T getData() {
    return data;
}

public void setData(T data) {
    this.data = data;
}

private void setParent(MyTreeNode parent) {
    this.parent = parent;
}

public MyTreeNode getParent() {
    return parent;
}

}

当我打印根节点的子节点时,我会得到这样的结果:[0,4]。理想情况下,我想将孩子打印为(0,4),因为这表示一组。我知道我需要覆盖.toString,但是当我不在树类中传递参数时,我怎么能这样做呢。

以下是JSON文件的示例:

{
"declaration-list" : [
    {
        "declared-variable" : "x0",
        "value" : 1
      },
    {
        "declared-variable" : "x212",
        "value" : {
            "operator" : "pair",
            "arguments" : [
                1,
                2
              ]
          }
      },
    {
        "declared-variable" : "x213",
        "value" : {
            "operator" : "pair",
            "arguments" : [
                3,
                4
              ]
          }
      },
    {
        "declared-variable" : "x3",
        "value" : {
            "operator" : "set",
            "arguments" : [
                {
                    "variable" : "x212"
                  },
                {
                    "variable" : "x213"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x214",
        "value" : {
            "operator" : "pair",
            "arguments" : [
                0,
                4
              ]
          }
      },
    {
        "declared-variable" : "x215",
        "value" : {
            "operator" : "pair",
            "arguments" : [
                1,
                6
              ]
          }
      },
    {
        "declared-variable" : "x10",
        "value" : {
            "operator" : "set",
            "arguments" : [
                {
                    "variable" : "x214"
                  },
                {
                    "variable" : "x215"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x216",
        "value" : {
            "operator" : "set",
            "arguments" : [
                8
              ]
          }
      },
    {
        "declared-variable" : "x8",
        "value" : {
            "operator" : "set",
            "arguments" : [
                {
                    "variable" : "x216"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x217",
        "value" : {
            "operator" : "set",
            "arguments" : [
                {
                    "variable" : "x8"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x8",
        "value" : {
            "operator" : "set",
            "arguments" : [
                {
                    "variable" : "x8"
                  },
                {
                    "variable" : "x217"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x17",
        "value" : {
            "operator" : "set",
            "arguments" : [
                1,
                2,
                {
                    "variable" : "x8"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x218",
        "value" : {
            "operator" : "pair",
            "arguments" : [
                1,
                {
                    "variable" : "x17"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x18",
        "value" : {
            "operator" : "set",
            "arguments" : [
                {
                    "variable" : "x17"
                  },
                {
                    "variable" : "x218"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x19",
        "value" : {
            "operator" : "pair",
            "arguments" : [
                {
                    "variable" : "x18"
                  },
                {
                    "variable" : "x17"
                  }
              ]
          }
      },
    {
        "declared-variable" : "x219",
        "value" : {
            "operator" : "set",
            "arguments" : [
                0
              ]
          }
      },

    {
        "declared-variable" : "x221",
        "value" : {
            "operator" : "set",
            "arguments" : [
                {
                    "variable" : "x219"
                  },
                {
                    "variable" : "x220"
                  }
              ]
          }
      },

    {
        "declared-variable" : "x224",
        "value" : {
            "operator" : "set",
            "arguments" : [
                2,
                1
              ]
          }
      },

    {
        "declared-variable" : "x225",
        "value" : {
            "operator" : "set",
            "arguments" : [
                {
                    "variable" : "x19"
                  }
              ]
          }
      },
  ]

}

2 个答案:

答案 0 :(得分:0)

很抱歉,如果这是一个粗略的答案,但您可以添加以下方法或类似于MyTreeNode类的方法。如果你知道任何类型T的类在调用getData()时将采用“[x,y]”的格式,这将有效:

void printData() {
    String t = (String)getData();
    t.replace("[", "(");
    t.replace("]", ")");
    System.out.println(t);
}

编辑:更新了评论澄清的代码:

void printData() {
    String t = (String)getData();
    if(t.startsWith("{") && t.endsWith("}")) {
        t.replace("{", "(");
        t.replace("}", ")");
    }
    else if(t.startsWith("[") && t.endsWith("]")) {
        t.replace("[", "(");
        t.replace("]", ")");
    }
    System.out.println(t);
}

答案 1 :(得分:0)

实现此目的的一种方法是使用自定义toString()方法编写包装类,您可以在其中定义如何输出JSONArray的元素。

这看起来像这样:

public class MyArrayNode {

    private JSONArray array;

    public MyArrayNode(JSONArray array) {
        this.array = array;
    }

    public JSONArray getArray() {
        return array;
    }

    @Override
    public String toString() {
        StringJoiner sj = new StringJoiner(",", "(", ")");
        array.forEach(a -> sj.add(a.toString()));
        return sj.toString();
    }
}

如果你想打印出这样的JSONArray,只需制作你的MyTreeNode即可 包含MyArrayNode类型元素:

      final JSONArray arguments = (JSONArray) jsonValue.get("arguments");
      if (operator.equals("set")) {
         MyTreeNode<MyArrayNode> test1 = new MyTreeNode(new MyArrayNode(arguments));