我想將以下內容作爲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)
請給出異常堆棧跟蹤 – Nailgun 2013-02-27 07:24:17
請添加堆棧跟蹤,並在哪一行獲得NPE。 – BobTheBuilder 2013-02-27 07:24:24