我试图从DownloadTask获取JsonObject。但我得到的数据值与存储在jsonObjectText中的JsonObjects一起存储在downloadData中。在日志中查看以下内容。 为什么我的代码使用JsonObject返回数组 ,但我只记录了jsonObject变量的内容。
这里的日志图片:
这是我的代码:
package com.example.smarpitsingh.webview;
public class MainActivity extends AppCompatActivity {
String name = "Result";
String result = "",downloadedData,jsonObjectText;
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
InputStreamReader streamReader;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
DownloadTask downloadTask = new DownloadTask();
try {
downloadedData = downloadTask.execute("https://hacker-news.firebaseio.com/v0/topstories.json?print=pretty").get();
JSONArray jsonArray = new JSONArray(downloadedData);
for (int i=1; i<20; i++){
DownloadTask jasonTask = new DownloadTask();
jsonObjectText = jasonTask.execute("https://hacker-news.firebaseio.com/v0/item/"+jsonArray.getString(i)+".json?print=pretty").get();
Log.i(name,jsonObjectText);
}
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
public class DownloadTask extends AsyncTask<String,Void,String>{
@Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection)url.openConnection();
inputStream = httpURLConnection.getInputStream();
streamReader = new InputStreamReader(inputStream);
int data = streamReader.read();
while (data != -1){
char count = (char)data;
result += count;
data = streamReader.read();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
}
}
`}`