为了账号安全,请及时绑定邮箱和手机立即绑定

如何在获取整个 JSON 数据源的同时获取某个标签

如何在获取整个 JSON 数据源的同时获取某个标签

喵喵时光机 2022-05-25 15:37:22
我想在 JSON 文件中记录一些标签的值。这是我的数据源:http ://data.nba.net/10s/prod/v1/2016/players.json我设法使用此处找到的代码获取整个数据流:使用 Android 从 URL 获取 JSON 数据?我发布它是为了让您更容易检查我的代码:    Button btnHit;TextView txtJson;ProgressDialog pd;@Overrideprotected 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...... :-)            }我的问题是我无法从我选择的来源获得单个标签。例如,我如何获取该流中每个玩家的名字和姓氏并记录下来?感谢您的时间和考虑。
查看完整描述

1 回答

?
MM们

TA贡献1886条经验 获得超2个赞

首先,我建议您使用任何用于 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();

}


查看完整回答
反对 回复 2022-05-25
  • 1 回答
  • 0 关注
  • 246 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号