NullPointerException while reading JSONArray passing String

2

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);
}
    
asked by anonymous 27.06.2018 / 16:35

1 answer

1

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

The correct way is to first access 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 compactly, without declaring 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 on 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
    
28.06.2018 / 21:06