2
This is my code, which gets a JSON format string from the url https://servicodados.ibge.gov.br/api/v1/localidades/estados
When extracting 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;
}
}
}
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 [which try to get the site string]) is used in an android project and works perfectly. But when trying to apply in a java project, I can’t get results.
When running in debug mode, I see that the error is on the line
estado = new JSONObject(jsonArray.getString(i));
but I cannot understand why this nullpointer is happening
Class/Metodo 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);
}
I put right at the beginning of the question the URL that returns the JSON.
– Pedro Henrique