You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android开发新手求助:如何从接口JSON中提取指定字段?

解决Android JSON解析获取指定字段的问题

首先,你的思路方向是对的!不过有几个小细节需要调整,咱们一步步来修正:

1. 先确认你的JSON数据格式

你给出的JSON片段应该是完整的这个结构(补全了缺失的大括号):

{"data":[{"id":1,"temperature":"21.375","humidity":"28"}]}

2. 你的AsyncTask需要先修正几个小问题

  • 初始化数据拼接变量,避免空指针;用StringBuilder代替直接字符串拼接,效率更高
  • 删掉onPostExecute里多余的ScrollingMovementMethod());代码行
  • GET请求不需要设置setDoOutput(true),因为不需要向服务器写入数据
  • 调整AsyncTask的返回类型为String,直接传递获取到的JSON字符串,比成员变量更安全

修正后的AsyncTask部分:

private class JsonConnection extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... voids) {
        String username = "websiteUsername";
        String password = "websitePassword";
        String credentials = username + ":" + password;
        String sensorID = "1";
        String api = "api";
        String websiteURL = "https://" + credentials + "@website.com" + "/" + sensorID + "/" + api;
        String credBase64 = Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT).replace("\n", "");
        StringBuilder dataBuilder = new StringBuilder();

        try {
            URL url = new URL(websiteURL);
            HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
            String basicAuth = "Basic " + new String(Base64.encode(credentials.getBytes(), Base64.URL_SAFE));
            connection.setRequestProperty("Authorization", basicAuth);
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("Content-Language", "en-US");
            connection.setUseCaches(false);
            connection.setDoInput(true);
            connection.connect();

            InputStream stream = connection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                dataBuilder.append(line);
            }
            bufferedReader.close();
            stream.close();
            connection.disconnect();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return dataBuilder.toString();
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pd = new ProgressDialog(MainActivity.this);
        pd.setMessage("Please wait");
        pd.setCancelable(false);
        pd.show();
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        if (pd.isShowing()) {
            pd.dismiss();
        }
        if (result != null) {
            System.out.println("获取到的JSON数据: " + result);
            parseRequiredJsonFields(result); // 调用专门的解析方法
        }
    }
}

3. 正确的JSON解析代码

你的核心疑问是构造JSONObject的参数,其实传入整个返回的JSON字符串(也就是上面的result)是完全正确的,问题出在这几个地方:

  • JSON里的temperature是带小数的字符串,不能用getInt(),应该用getDouble()或者先转字符串再转换
  • humidity是字符串类型的整数,可以直接用getInt()(JSON库会自动处理字符串转整数)
  • 不要解析你的JSON里不存在的字段(比如battery、mode等),否则会抛出JSONException

修正后的解析方法:

private void parseRequiredJsonFields(String jsonData) {
    try {
        JSONObject parentObject = new JSONObject(jsonData);
        JSONArray parentArray = parentObject.getJSONArray("data");
        // 先判断数组是否有数据,避免索引越界
        if (parentArray.length() > 0) {
            JSONObject finalObject = parentArray.getJSONObject(0);
            // 获取你需要的三个字段
            int id = finalObject.getInt("id");
            double temperature = finalObject.getDouble("temperature");
            int humidity = finalObject.getInt("humidity");

            // 打印结果或者更新UI
            System.out.println("id: " + id + ", temperature: " + temperature + ", humidity: " + humidity);
            // 比如更新TextView展示数据:
            // tempTextView.setText("温度: " + temperature + "℃");
            // humTextView.setText("湿度: " + humidity + "%");
        }
    } catch (JSONException e) {
        e.printStackTrace();
        // 可以在这里添加解析失败的提示,比如Toast
        // Toast.makeText(MainActivity.this, "数据解析失败", Toast.LENGTH_SHORT).show();
    }
}

4. 额外提示

  • 记得在AndroidManifest.xml里添加网络权限:<uses-permission android:name="android.permission.INTERNET" />
  • 作为新手,先掌握基础的HTTP请求和JSON解析是很好的,之后可以尝试用更现代的库(比如Retrofit + Gson),代码会更简洁且不易出错

内容的提问来源于stack exchange,提问作者Buster3650

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:38:52