这个问题在这里已有答案:
我是Android Studio的新手,我想使用omdb.com上的API获取一些数据,以下是我的工作方式:
我创建了一个类:
package com.example.emad.apidemo;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class fetchData extends AsyncTask<Void,Void,Void> {
public String data = "";
public String Title ="";
@Override
protected Void doInBackground(Void... voids) {
try {
URL url = new URL("http://www.omdbapi.com/?t=the+generation&apikey=42ae84fb");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line = "";
while(line != null){
line = bufferedReader.readLine();
data = data + line;
}
JSONArray JA = new JSONArray(data);
JSONObject JO = JA.getJSONObject(0);
Title = JO.getString("Title");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.txtResponse.setText(this.Title);
}
}
我想从以下JSON获取Title
值:
{
"Title": "The Generation Game",
"Year": "1971–2001",
}
这是我的mainActivity代码:
public void btnFetchData_CLick(View v){
fetchData process = new fetchData();
process.execute();
}
当我点击按钮时,没有任何反应!
为什么我无法访问任何价值?
你的JSON是JsonObject而不是JsonArray,所以你应该这样做:
JSONObject JO = new JSONObject(data);
然后,如果你想获得标题,请执行以下操作:
title = JO.getString("Title")
;
你拥有的唯一JSONArray就是这个:
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "6.6/10"
}],