我想在 JSON 文件中记录一些标签的值。 这是我的数据源:http://data.nba.net/10s/prod/v1/2016/players.json
我设法使用此处找到的代码获取了整个数据流:Get JSON Data from URL Using Android?我发布它是为了让您更容易检查我的代码:
Button btnHit;
TextView txtJson;
ProgressDialog pd;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnHit = (Button) findViewById(R.id.btnHit);
txtJson = (TextView) findViewById(R.id.tvJsonItem);
btnHit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new JsonTask().execute("http://data.nba.net/10s/prod/v1/2016/players.json");
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
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+"\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException 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);
if (pd.isShowing()){
pd.dismiss();
}
txtJson.setText(result);
}
}
}
我的问题是我无法从我选择的源中获取单个标签。例如,我如何获取该流中每个玩家的名字和姓氏并将其记录下来?
感谢您的时间和考虑。
最佳答案
首先,我建议您使用任何适用于 android 的 http 库(okHttp、volley..)
但是如果你仍然想使用你实现它的方式,你需要在这里做一些改变:
while ((line = reader.readLine()) != null) {
buffer.append(line);
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
String json = buffer.toString();
try {
String json = "";
JSONObject jsonObject = new JSONObject(json);
JSONObject league = jsonObject.getJSONObject("league");
JSONArray standard = league.getJSONArray("standard");
for (int i = 0;i<standard.length();i++){
JSONObject item = standard.getJSONObject(i);
String name = item.getString("firstName");
String lastName= item.getString("lastName");
}
} catch (JSONException e) {
e.printStackTrace();
}
关于java - 如何在获取整个JSON数据源的同时获取某个标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54420813/