Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 处理不同的JSONArray类型_Java_Json_Tree - Fatal编程技术网

Java 处理不同的JSONArray类型

Java 处理不同的JSONArray类型,java,json,tree,Java,Json,Tree,我有一个程序,读取一个简单的JSON文件并处理数据。然后,我将这些数据存储在树中(尽管很糟糕)。我有一个问题,参数可以是long,比如{1,2},long和变量,比如{1,x2},或者变量和其他变量,比如{x1,x2} 我已经能够从JSONArray中检索变量。当我有一个变量和一个值时,问题就出现了。我一辈子都想不出如何处理这样的事情。对于过度使用try-catch操作,我深表歉意。如果有人能帮我解决这个问题,我将不胜感激 public class program { public stati

我有一个程序,读取一个简单的JSON文件并处理数据。然后,我将这些数据存储在树中(尽管很糟糕)。我有一个问题,参数可以是long,比如{1,2},long和变量,比如{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();

}
公共类程序{
公共静态void main(字符串[]args)引发IOException{
File File=新文件();
File outputfile=新文件();
PrintWriter pw=新的PrintWriter(新的BufferedWriter(新的
FileWriter(outputfile,true));
JSONParser=新的JSONParser();
试一试{
//创建已解析文件的对象
Object=parser.parse(新文件读取器(文件));
//将对象强制转换为jsonObject
JSONObject JSONObject=(JSONObject)对象;
//从创建的对象获取声明列表JSONArray。
JSONArray JSONArray=(JSONArray)jsonObject.get(“声明列表”);
//围绕着这一点,我可以试着去解决这个问题
//不同的价值案例不同于我第一次写它
试一试{
/*
*迭代器循环遍历数组。上次出错
*连续调用方法的时间
*/
迭代器迭代器=jsonArray.Iterator();
while(iterator.hasNext()){
JSONObject jo=(JSONObject)迭代器.next();
字符串variableName=(String)jo.get(“声明的变量”);
MyTreeNode根=新的MyTreeNode(variableName);
试一试{
long value=(long)jo.get(“value”);
MyTreeNode child1=新的MyTreeNode(值);
System.out.println(root.getData());
root.addChild(child1);
对于(MyTreeNode节点:root.getChildren()){
System.out.println(node.getData());
}
测试。输入(变量名称、值);
//numPrint(测试,变量名称,pw);
}捕获(例外e){
最终JSONObject jsonValue=(JSONObject)jo.get(“value”);
最终字符串运算符=(字符串)jsonValue.get(“运算符”);
最终JSONArray参数=(JSONArray)jsonValue.get(“参数”);
ArrayList值[]=新ArrayList[arguments.size()];
if(运算符等于(“set”)){
对于(int i=0;i
}

MyTreeNode类{
私有T数据=null;
private List children=new ArrayList();
private MyTreeNode parent=null;
公共MyTreeNode(T数据){
这个数据=数据;
}
public void addChild(MyTreeNode child){
child.setParent(this);
this.children.add(child);
}
公共void addChild(T数据){
MyTreeNode newChild=新MyTreeNode(数据);
newChild.setParent(this);
添加(newChild);
}
公共子项(列出子项){
用于(MyTreeNode t:儿童){
t、 setParent(本);
}
this.children.addAll(children);
}
公共列表getChildren(){
返回儿童;
}
公共T getData(){
返回数据;
}
公共无效设置数据(T数据){
这个数据=数据;
}
私有void setParent(MyTreeNode父级){
this.parent=parent;
}
公共MyTreeNode getParent(){
返回父母;
}
}

类myObject{
字符串运算符;
JSONArray论点;
公共myObject(字符串运算符、JSONArray参数){
this.operator=操作员;
this.arguments=参数;
}
公共JSONArray get(){
返回参数;
}
公共字符串toString(){
if(arguments.size()==0){
返回“{}”;
}
if(运算符等于(“对”)){
返回“(“+arguments.get(0)+”,“+arguments.get(1)+”);
}else if(运算符等于(“set”)){
字符串concat=“{”+arguments.g
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";

}
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);
        }
    });
}
{
  "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);
        }
    }
}
declared-variable
x17
value
arguments
1
2
variable
x8
operator
set