java - Android Studio - 加载 JSON 时出现问题

标签 java android

我正在使用 Android Studio,我想创建一个 ListView ,其中包含通过 JSON 接收的值。

 protected Void doInBackground(Void... voids) {
    HttpHandler Handler = new HttpHandler();
    String JSONString = Handler.makeServiceCall(JSONUrl);
    Log.e(TAG, "Response:" + JSONString);

    if(JSONString != null){
        try {
            JSONObject CountriesJSONObject = new JSONObject(JSONString);

            JSONArray Countries = CountriesJSONObject.getJSONArray("countries");

            for (int i = 1; i < Countries.length(); i++) {
                JSONObject Country = Countries.getJSONObject(i);

                //Details
                String CountryID = Country.getString("id");
                String CountryName = Country.getString("name");
                String CountryImage = Country.getString("image");

                //Hashmap
                HashMap<String, String> TempCountry = new HashMap<>();

                //Details to Hashmap
                TempCountry.put("id", CountryID);
                TempCountry.put("name", CountryName);
                TempCountry.put("image", CountryImage);

                //Hashmap to Countrylist
                CountryList.add(TempCountry);
            }
        } catch (final JSONException e){
            Log.e(TAG,e.getMessage());
            ProgressDialog.setMessage("Error loading Data!");

    }

    }
        return null;
    }

这是获取 JSON 值的代码,但我收到错误 “id 没有值” 我做错了什么?

最佳答案

您仍然需要打开“国家/地区” key 。尝试这样:

for (int i = 1; i < Countries.length(); i++) {
                JSONObject Country = Countries.getJSONObject(i).getJSONObject("country");

                //Details
                String CountryID = Country.getString("id");
                String CountryName = Country.getString("name");
                String CountryImage = Country.getString("image");

                //Hashmap
                HashMap<String, String> TempCountry = new HashMap<>();

                //Details to Hashmap
                TempCountry.put("id", CountryID);
                TempCountry.put("name", CountryName);
                TempCountry.put("image", CountryImage);

                //Hashmap to Countrylist
                CountryList.add(TempCountry);
            }

关于java - Android Studio - 加载 JSON 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50435800/

相关文章:

java - EJB 3.1 @Schedule 可以在应用程序代码之外配置吗?

java - 如何使用 RestEasy 验证冗余查询参数?

java - Android AES/CBC 加密

android - 在 imageview 中设置图像,使其看起来像进度条

java - Android 应用程序在启动新 Intent 时崩溃

java - 通过 Flume 将 API 数据传输到 hadoop

java - 如何强制卸载应用程序以进行更新?

android - 选择客户端应用程序或 Web 应用程序时要考虑的因素

android - 签名 apk 可以在 Android Studio 中运行,但为什么相同的 keystore 不能在命令行上运行?

android - 如何检查是否可以在 API 30+(Android 10+,R)上处理 Intent ?