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:
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?