我已经阅读了我的 JSONData,现在我想将“名称”键显示到组合框中。但是我得到了我的字符串数组的空指针异常。在我尝试将 JSON 对象直接发送到 defaultComboBoxModel 之前。但它必须是字符串数组,所以当我转换它时,一切都变成了空值。为什么我的数组为空?
我的代码:
import java.util.ArrayList;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class Planner {
private String startingLocation;
private String destination;
private static Planner planner = null;
private int id;
private JSONArray array;
ArrayList myList = new ArrayList();
public static Planner getPlanner(){
if (planner == null ){
planner = new Planner();
}
return planner;
}
public void setStartingLocation(String from) {
this.startingLocation = from;
}
public void setDestination(String dest) {
this.destination = dest;
}
public String getStartingLocation() {
return startingLocation;
}
public String getDestination() {
return destination;
}
public void setID(int id) {
this.id = id;
}
public void setLocationName (JSONArray array){
this.array = (JSONArray) array;
}
public String[] getLocationName(){
System.out.println(this.array.size());
for (int i=0; i<this.array.size(); i++){
myList = (ArrayList) this.array.get(i);
myList.add(i, array);
}
System.out.println(myList);
return (String[]) myList.toArray();
}
}
public void parseJsonData() throws ParseException {
JSONParser parser = new JSONParser();
Object obj = parser.parse(jsonData);
JSONObject topObject = (JSONObject) obj;
JSONObject locationList = (JSONObject) topObject.get("LocationList");
JSONArray array = (JSONArray) locationList.get("StopLocation");
Iterator<JSONObject> iterator = array.iterator();
String name = null;
while (iterator.hasNext()) {
JSONObject jsonObj = (JSONObject) iterator.next();
Planner.getPlanner().setLocationName(array);
}
}
final DefaultComboBoxModel model = new DefaultComboBoxModel(Planner.getPlanner().getLocationName());
comboBox = new JComboBox(model);