我想将以下内容作为 Json 输入并将其转换为 java 中的树数据结构。
{
"component": "A",
"status": 0,
"children": [
{
"component": "AA",
"status": 0,
"children": [
{
"component": "AAA",
"status": 0,
"children": []
},
{
"component": "AAB",
"status": 0,
"children": []
}
]
},
{
"component": "AB",
"status": 0,
"children": [
{
"component": "ABA",
"status": 0,
"children": []
},
{
"component": "ABB",
"status": 0,
"children": []
}
]
}
}
我编写了以下代码,但如果有人能找到错误,它会显示运行时错误。当它应该返回显示空指针异常的位置时,for循环正在执行直到通过递归没有节点的子节点
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import java.io.BufferedReader;
import org.json.*;
public class Sample {
public static void main(String[] args) {
BufferedReader in = new BufferedReader( new FileReader("json.txt") );
StringBuilder builder = new StringBuilder();
String line;
while ( ( line = in.readLine() ) != null ) {
builder.append(line);
object = new JSONObject( builder.toString() );
imlementation im = new imlementation();
im.createnode(object);
}
}
public class node {
public String component;
public int status;
public List<node> children;
}
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class imlementation {
public node createnode(JSONObject ob)
{
node n = new node();
try
{
JSONArray children = ob.getJSONArray("children");
String component = ob.getString("component");
int status = ob.getInt("status");
n.component = component;
n.status = status;
n.children=null;
System.out.println( "component " + component + "status " + status );
int i;
for(i=0;i<children.length();i++)
{
n.children.add( createnode( children.getJSONObject( i ) ) );
}
return n;
}
catch ( JSONException ex )
{
ex.printStackTrace();
}
}
}
堆栈跟踪是
java.lang.NullPointerException
at imlementation.createnode(imlementation.java:30)
at imlementation.createnode(imlementation.java:30)
at SampleSample.main(SampleSample.java:45)
java.lang.NullPointerException
at imlementation.createnode(imlementation.java:30)
at SampleSample.main(SampleSample.java:45)