This is my code, which receives a String in JSON format from the url link
When extracting the data, according to this class / method public class JSONDataHandler {
public List<String> extractDados(String string) {
List<String> dados = new ArrayList<>();
try {
JSONArray jsonArray = new JSONArray(string);
JSONObject estado;
for (int i = 0; i < jsonArray.length(); i++) {
estado = new JSONObject(jsonArray.getString(i));
dados.add(estado.get("sigla").toString());
}
return dados;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
}
I get the error message:
org.json.JSONException: JSONArray[0] not a string.
at org.json.JSONArray.getString(JSONArray.java:329)
at utils.JSONDataHandler.extractDados(JSONDataHandler.java:20)
at main.Main.gerarEstado(Main.java:40)
at main.Main.main(Main.java:21)
Exception in thread "main" java.lang.NullPointerException
at main.Main.main(Main.java:23)
But this same method (with the other HTTPREsponse and HTTPCall classes) are used in an android project and work perfectly. But when trying to apply to a java project, I can not get results.
When running in debug mode, I see that the error is on the line
estado = new JSONObject(jsonArray.getString(i));
But I can not understand why this nullpointer is happening
Class / Method main
public static void main(String[] args) {
StringBuilder construtorString = new StringBuilder();
List<String> estadosArray = gerarEstado();
for (String estado : estadosArray) {
System.out.println(estado);
construtorString.append(estado).append(System.lineSeparator());
}
}
private static List<String> gerarEstado() {
HTTPCall estadoHTTP = new HTTPCall(URL_ESTADOS);
String respondeStr = null;
try {
HTTPResponse response = estadoHTTP.execute(HTTPCall.Method.GET);
respondeStr = response.extractDataAsString();
} catch (IOException ioe) {
Logger.getLogger(Level.SEVERE + " " + Main.class.getName() + " " + ioe);
}
return new JSONDataHandler().extractDados(respondeStr);
}