'Accessing a JSON array inside of a JSON object in Android Studio
I am testing my knowledge and ability with android studio and API's, I have been using volley and I have come across a little problem.
The API I have been using is the Ergast F1 API, this is the exact link I am using
https://ergast.com/api/f1/2019/drivers.json
I think my problem is that I am trying to access the array 'Drivers' but nothing seems to be working, I think this might be because it is inside the 'DriverTables' object, I may be completely wrong, like I say I am only learning.
This is my code here, any help is greatly appreciated
public class MainActivity extends AppCompatActivity {
private TextView mTextViewResult;
private RequestQueue mQueue;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTextViewResult = findViewById(R.id.textViewResult);
Button buttonParse = findViewById(R.id.parse);
mQueue = Volley.newRequestQueue(this);
buttonParse.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
jsonParse();
}
});
}
private void jsonParse() {
String url = "https://ergast.com/api/f1/2019/drivers.json";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
response - > {
try {
JSONArray jsonArray = response.getJSONArray("Drivers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject driver = jsonArray.getJSONObject(i);
String firstName = driver.getString("givenName");
String lastName = driver.getString("familyName");
String nationality = driver.getString("nationality");
mTextViewResult.append(firstName + ", " + lastName + ", " + nationality + "\n\n");
}
} catch (JSONException e) {
e.printStackTrace();
}
},
error - > error.printStackTrace());
mQueue.add(request);
}
}
Solution 1:[1]
Since your MRData is main JSONObject and you are trying to fetch "Drivers" child array from "DriverTable" object, you have to get "DriverTable" first from your JSON response.
MRData -DriverTable -Drivers
Try following Code:
JSONObject driverTable = response.getJSONObject("DriverTable");
JSONArray jsonArray = driverTable.getJSONArray("Drivers");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject driver = jsonArray.getJSONObject(i);
String firstName = driver.getString("givenName");
String lastName = driver.getString("familyName");
String nationality = driver.getString("nationality");
mTextViewResult.append(firstName + ", " + lastName + ", " + nationality + "\n\n");
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Raghubeer singh virk |