我希望将以下内容作为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)
答案 0 :(得分:1)
您已设置
n.children=null;
然后在for循环中你正在做
n.children.add(....)
可能导致Null指针异常。
你可能需要做
n.children = new List<Node>()
在进行添加之前。
另一个可能的原因是在一些递归调用期间,children变量可以为null。 children.length会导致空指针异常。