【问题标题】:how can i return JSONObject data as array如何将 JSONObject 数据作为数组返回
【发布时间】:2015-02-06 10:03:03
【问题描述】:

我正在尝试将 JSONObject 中的数据作为数组返回,以便循环遍历它们。在 udacity 上进行了 android 开发培训,但培训中使用的 JSON 结构与我使用的不同。下面是我的课

  private String[] getWeatherDataFromJson(String forecastJsonStr)
            throws JSONException {

        // These are the names of the JSON objects that need to be extracted.
        final String OWM_LIST = "rules";
        final String OWM_DESCRIPTION = "game_rules_content";

        JSONObject forecastJson = new JSONObject(forecastJsonStr);
        JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
        Log.v(LOG_TAG, "success: " + forecastJson.getInt("success"));

       //I guess my problem is starts here
       String[] resultStrs = new String[1];

        for(int i = 0; i < weatherArray.length(); i++) {

            String rule;
            // Get the JSON object representing the day
            JSONObject dayForecast = weatherArray.getJSONObject(i);
            rule = dayForecast.getString(OWM_DESCRIPTION);
            Log.v(LOG_TAG, "sammy: " + rule);

             // how do i return my json data as array for i loop through the array with for
            resultStrs[0] = rule;

        }

        for (String s : resultStrs) {
            Log.v(LOG_TAG, "Forecast entry: " + s);
        }
        return resultStrs;

    }

【问题讨论】:

    标签: android arrays json


    【解决方案1】:

    您可以发布链接获取 json 或您的 json。如果你可以尝试使用 gson 库来解析 json,例如:gson example

    【讨论】:

      【解决方案2】:

      你应该编写这样的代码。

       resultStrs[i] = rule;
      

      这将解决您的问题。 干杯。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-25
        • 2014-05-20
        • 1970-01-01
        • 1970-01-01
        • 2017-01-20
        • 1970-01-01
        • 2019-04-14
        • 1970-01-01
        相关资源
        最近更新 更多