gpt4 book ai didi

java - 处理不同的 JSONArray 类型

转载 作者:行者123 更新时间:2023-12-02 11:38:25 25 4
gpt4 key购买 nike

我有一个程序可以读取一个简单的 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";

}

}

最佳答案

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

如果数组中有数组,这将允许您重复使用代码,并且还可以在 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"
}
]
}
}

您可以通过创建与此类似的 main 方法来实现此目的:

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

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

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

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

关于java - 处理不同的 JSONArray 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48753147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com