Я впервые работаю с Android, и мне нужно проанализировать JSON, вложенный в API. В приведенном ниже примере мне удалось проанализировать один JSON объект, значение "title" равно https://jsonplaceholder.typicode.com/posts/1. Как изменить код, чтобы просмотреть все JSON объекты в l oop и извлечь из них «title» - https://jsonplaceholder.typicode.com/posts/?
PS Если возможно, я бы не хотел использовать новые зависимости Maven / Gradle.
package org.newwheel.app;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.JsonReader;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.HttpsURLConnection;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new RequestAsync().execute();
}
public class RequestAsync extends AsyncTask<String,String,List<String>> {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected List<String> doInBackground(String... strings) {
List<String> projectList = new ArrayList<>();
try {
// Create URL
URL newWheelEndpoint = new URL("https://jsonplaceholder.typicode.com/posts/1");
// Create connection
HttpsURLConnection myConnection = (HttpsURLConnection) newWheelEndpoint.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, StandardCharsets.UTF_8);
JsonReader jsonReader = new JsonReader(responseBodyReader);
jsonReader.beginObject(); // Start processing the JSON object
while (jsonReader.hasNext()) { // Loop through all keys
String key = jsonReader.nextName(); // Fetch the next key
if (key.equals("title")) { // Check if desired key
// Fetch the value as a String
String value = jsonReader.nextString();
// Do something with the value
// ...
projectList.add(value);
break; // Break out of the loop
} else {
jsonReader.skipValue(); // Skip values of other keys
}
}
jsonReader.close();
myConnection.disconnect();
} else {
// Error handling code goes here
}
} catch (IOException e) {
e.printStackTrace();
}
return projectList;
}
@Override
protected void onPostExecute(List<String> list) {
if(list!=null){
String[] array = list.toArray(new String[0]);
// Get element ListView
ListView countriesList = (ListView) findViewById(R.id.countriesList);
// Create adapter
ArrayAdapter<String> adapter = new ArrayAdapter(MainActivity.this,
android.R.layout.simple_list_item_1, array);
// Install for list adapter
countriesList.setAdapter(adapter);
}
}
}
}