我一直在遵循一个教程,该教程提供了一个可在json请求中使用的示例网站,但是当我放入自己的网站中以从中抓取数据时,什么也没发生。
这是我的代码;
private TextView tvData;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvData = (TextView) findViewById(R.id.tvJsonItem);
new JSONTask().execute("http://jsonparsing.parseapp.com/jsonData/moviesDemoItem.txt");
}
public class JSONTask extends AsyncTask<String,String, String>{
@Override
protected String doInBackground(String ... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("movies");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("movie");
String mostGames = finalObject.getString("year");
return ChampionName + mostGames;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
tvData.setText(result);
}
}
}
当它在左边工作时的屏幕,当它不在右边工作时的屏幕。
是的,这就是我知道我必须改变的
new JSONTask().execute("http://api.champion.gg/champion/Ekko");
和
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("WHAT DO I PUT HERE");
JSONObject finalObject = parentArray.getJSONObject(0);
String ChampionName = finalObject.getString("WHAT DO I PUT HERE");
String mostGames = finalObject.getString("WHAT DO I PUT HERE");
从这个URL-http://api.champion.gg/champion/Ekko/,我想让我们说一下前两个字段“ key”:“ Ekko”,“ role”:“ Top”,所以如果有人可以帮我,那太好了!
最佳答案
根据返回的JSON,您的链接http://api.champion.gg/champion/Ekko/
您必须开始将字符串响应解析为JSONArray
JSONArray parentObject = new JSONArray(finalJson);
然后开始遍历此数组以获取JSONObject
JSONObject jsonObject = parentObject.getJSONObject(yourLoopIndex);
在每个JSONObject内,您可以获得任何值。通过使用原始JSON字符串中的键。