我想将一些标签的值记录在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);
}
}
}
我的问题是我无法从选择的来源获得单个标签。例如,如何获取该流中每个玩家的名字和姓氏并将其记录下来?
感谢您的时间和考虑。
答案 0 :(得分:2)
首先,我建议您使用适用于android的任何http库(okHttp,凌空..)
但是,如果您仍然想使用实现方式,则需要在此处进行一些更改:
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();
}