1

My question is very easy. Please look at this JSON source: JSON API LINK.

Here's the code to parse the QualifyingResults to get these fields: position, Q1, Q2 and Q3.

private static void parseJsonData(String json) {
        JsonElement root = new JsonParser().parse(json);
        JsonObject rootObj = root.getAsJsonObject();

        JsonArray schedulesPath = rootObj.getAsJsonObject("MRData")
                .getAsJsonObject("RaceTable")
                .getAsJsonArray("Races");

        if (schedulesPath.size() > 0) {
            int pos = 1;

            JsonArray qualifyingsList = schedulesPath.get(0)
                    .getAsJsonObject()
                    .getAsJsonArray("QualifyingResults");

            for (JsonElement element : qualifyingsList) {
                JsonObject qualiTimes = element.getAsJsonObject();

                String driverName = qualiTimes.getAsJsonObject("Driver").get("familyName").getAsString();
                String Q1 = qualiTimes.get("Q1").getAsString();
                String Q2 = qualiTimes.get("Q2").getAsString();
                String Q3 = qualiTimes.get("Q3").getAsString();

                Log.d("quali_results", Q1 + " " + Q2 + " " + Q3);
            }
        }

    }

Why I am getting this error?

java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.google.gson.JsonElement.getAsString()' on a null object reference

As you can see here:

obl

position, Q1, Q2 and Q3 are attributes of the object item 0. Why then this throws the NullPointerException

String Q1 = qualiTimes.get("Q1").getAsString();
String Q2 = qualiTimes.get("Q2").getAsString();
String Q3 = qualiTimes.get("Q3").getAsString();

but this does not?

String Q1 = qualiTimes.get("position").getAsString();
String Q2 = qualiTimes.get("position").getAsString();
String Q3 = qualiTimes.get("position").getAsString();

Can it be a problem with GSON?

Raffaele Rossi
  • 2,997
  • 4
  • 31
  • 62

1 Answers1

2

get method is not safe in chained invocation. See documentation, @return:

the member matching the name. Null if no such member exists.

So, you need to check whether it is not null:

JsonElement q3Element = qualiTimes.get("Q3");
String Q3 = null;
if (q3Element != null) {
    Q3 = q3Element.getAsString();
}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146