java如何使用帮助JsonReader解析Android上的嵌套JSON?
这是我第一次使用Android,我需要解析API中嵌套的JSON。在下面的示例中,我设法解析了一个JSON对象,值“title”是https://jsonplaceholder.typicode.com/posts/1。如何更改代码以查看循环中的所有JSON对象并从中提取“title”https://jsonplaceholder.typicode.com/posts/
p.S.如果可能,我不想使用新的Maven/Gradle依赖项
package org.newwheel.app;
import 安卓.os.AsyncTask;
import 安卓.os.Build;
import 安卓.os.Bundle;
import 安卓.util.JsonReader;
import 安卓.widget.ArrayAdapter;
import 安卓.widget.ListView;
import 安卓x.annotation.RequiresApi;
import 安卓x.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,
安卓.R.layout.simple_list_item_1, array);
// Install for list adapter
countriesList.setAdapter(adapter);
}
}
}
}
共 (0) 个答案