Nullpointerexception when reading Jsonarray passing String

Asked

Viewed 64 times

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.

1 answer

1


Within the JSONArray, you have a collection of JSONObject and not String (therefore the message JSONArray[0] not a string.). To NullPointerException happens because you try to access estado which is still null because of previous error.

The correct way is to first access the JSONObject and then look for the key:

List<String> dados = new ArrayList<>();
try {
  JSONArray jsonArray = new JSONArray(string);
  JSONObject estado;
  for (int i = 0; i < jsonArray.length(); i++) {
     estado = jsonArray.getJSONObject(i);
     dados.add(estado.getString("sigla"));
  }
} catch (JSONException e) {
   e.printStackTrace();
}

However, you can do it more compact without the need to declare the variable estado:

//...
JSONArray jsonArray = new JSONArray(string);
for (int i = 0; i < jsonArray.length(); i++) {
     dados.add(jsonArray.getJSONObject(i).getString("sigla"));
}
//...

Using Java 8, it gets even more compact:

List<String> dados = new ArrayList<>();
try {
  new JsonArray(string).forEach(estado -> dados.add(((JSONObject) estado).getString("sigla")));
} catch (JsonException e) {
  e.printStackTrace();
}

If we print dados in any of the solutions, we will have:

//RO AC AM RR PA AP TO MA PI CE RN PB PE AL SE BA MG ES RJ SP PR SC RS MS MT GO DF
  • Huum, ball show. I understood now because I was wrong. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.