处理不同的JSONArray类型

时间:2018-02-12 18:29:44

标签: java json tree

我有一个程序,它读入一个简单的JSON文件并操纵数据。然后我将这些数据存储在树中(虽然很糟糕)。我有一个问题,其中参数可以长,例如{1,2},长整数和变量,例如{1,x2},或变量与其他变量,例如{X1,X2}。

我已经能够从JSONArray中检索变量。当我有变量和值时会出现问题。我不能为我的生活弄清楚如何处理这样的事情。我为过度使用try-catch操作道歉。如果有人能帮我解决这个问题,我将不胜感激。

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 {

        // creates object of parsed file
        Object object = parser.parse(new FileReader(file));

        // casts object to jsonObject
        JSONObject jsonObject = (JSONObject) object;

        // gets declaration-list JSONArray from the object created.
        JSONArray jsonArray = (JSONArray) jsonObject.get("declaration-list");

        // Surrounding this in a try-catch would allow me to deal with the
        // different value cases unlike the frist time i wrote it
        try {

            /*
             * iterator to cycle through the array. Made the mistake last
             * time of continuously calling a method
             */

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

                    test.put(variableName, value);

                    // numPrint(test, variableName, pw);

                } catch (Exception e) {

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

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

                    ArrayList values[] = new ArrayList[arguments.size()];


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


                        for(int i = 0; i < arguments.size(); i++){

                            try{

                            //prints nested variables   

                            JSONObject jtest = (JSONObject) arguments.get(i);
                            String varval = (String) jtest.get("variable");
                            System.out.println(varval);
                            }catch(Exception g){


                            }

                        }

                        MyTreeNode<myObject> test1 = new MyTreeNode(new myObject(operator, arguments));
                        root.addChild(test1);

                        for (MyTreeNode node : root.getChildren()) {

                            System.out.print(root.getData());
                            System.out.print(" = ");
                            System.out.println(node.getData());

                        }

                    }

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

                        MyTreeNode<myObject> test1 = new MyTreeNode(new myObject(operator, arguments));

                        root.addChild(test1);

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

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

                        }

                    }
                }
            }

        } catch (Exception e) {

            System.out.println("oops");
        }

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

}

class myObject {

String operator;
JSONArray arguments;

public myObject(String operator, JSONArray arguments) {

    this.operator = operator;
    this.arguments = arguments;

}

public JSONArray get() {
    return arguments;
}

public String toString() {

    if (arguments.size() == 0) {

        return "{}";
    }

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

        return "(" + arguments.get(0) + "," + arguments.get(1) + ")";

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

        String concat = "{" + arguments.get(0);

        for (int i = 1; i < arguments.size(); i++) {
            concat += "," + arguments.get(i);
        }

        return concat += "}";
    }

    return "wot";

}

}

1 个答案:

答案 0 :(得分:1)

为了处理JSONArray,我建议您先创建一个检查对象类型的方法,然后根据其类型将处理委托给其他专门方法。

这将允许您重复使用代码,以防您在数组中有数组并且还可以浏览JSON树。

这些方面的东西:

private static void processArray(JSONArray jsonArray) {
    jsonArray.forEach(o -> {
        if (o instanceof Number) {
            processNumber((Number) o);
        } else if (o instanceof JSONObject) {
            process((JSONObject) o);
        } else if (o instanceof String) {
            process((String) o);
        } else if (o instanceof JSONArray) {
            processArray((JSONArray) o); // recursive call here.
        }
    });
}

其他方法如下:

private static void process(String o) {
    System.out.println(o); // just an example
}

public static void processNumber(Number number) {
    System.out.println(number); // just an example
}

最复杂的是处理对象的那个:

private static void process(JSONObject o) {
    o.forEach((s, o1) -> {
        System.out.println(s);
        if (o1 instanceof Number) {
            processNumber((Number) o1);
        } else if (o1 instanceof JSONObject) {
            process((JSONObject) o1); // recursion
        } else if (o1 instanceof String) {
            process((String) o1);
        } else if (o1 instanceof JSONArray) {
            processArray((JSONArray) o1);
        }
    });
}

此方法也是递归的。使用这种方法,您可以浏览树中的所有对象。

<强>更新

如果您想处理JSON,请执行以下操作:

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

你可以通过创建一个类似于这个的主方法来实现:

public static void main(String[] args) throws IOException, ParseException {
    JSONParser jsonParser = new JSONParser(JSONParser.MODE_JSON_SIMPLE);
    try (InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("array_mixed.json")) {
        Object obj = jsonParser.parse(in);
        if (obj instanceof JSONArray) {
            processArray((JSONArray) obj);
        }
        else if(obj instanceof Object) {
            process((JSONObject) obj);
        }
    }
}

这个主要方法与所描述的其他方法一起至少可以打印出JSON中的所有元素。

在上面指定的JSON的情况下,您应该能够至少打印出以下内容:

declared-variable
x17
value
arguments
1
2
variable
x8
operator
set