Android - 如何从JSON数组中解析特定值并显示Toast

tlx*_*gum 0 java android json

一般是Android和Java的新手,我正在学习如何进行JSON调用.为此,我正在遵循本指南:http://mobiforge.com/design-development/consuming-json-services-android-apps

这就是让我感到困惑的地方.该教程的作者希望读者调用此API:http://ws.geonames.org/findNearByWeatherJSON? la = 37lng = 122

以这种格式返回JSON对象:

            {
                "weatherObservation": {
                     "clouds":"scattered clouds",
                     "weatherCondition":"n/a",
                     "observation":"KCFV 090852Z AUTO 06005KT 
                      10SM SCT090 SCT110 24/20 A3000 RMK AO2 
                      SLP148 T02390200 53002",
                     "windDirection":60,
                     "ICAO":"KCFV",
                     "seaLevelPressure":1014.8,
                     "elevation":225,
                     "countryCode":"US",
                     "lng":-95.56666666666666,
                     "temperature":"23.9",
                     "dewPoint":"20",
                     "windSpeed":"05",
                     "humidity":78,
                     "stationName":"Coffeyville, Coffeyville 
                                 Municipal Airport",
                     "datetime":"2012-07-09 08:52:00",
                     "lat":37.083333333333336
                }
            }
Run Code Online (Sandbox Code Playgroud)

非常简单,除了API不再有效/有限制.为了完成项目,我选择调用此API:http://api.openweathermap.org/data/2.5/weather?la = 37.77&rn = 1222.419

以这种格式返回JSON

{
    "coord": {
        "lon": 139,
        "lat": 35
    },
    "sys": {
        "country": "JP",
        "sunrise": 1369769524,
        "sunset": 1369821049
    },
    "weather": [
        {
            "id": 804,
            "main": "clouds",
            "description": "overcast clouds",
            "icon": "04n"
        }
    ],
    "main": {
        "temp": 289.5,
        "humidity": 89,
        "pressure": 1013,
        "temp_min": 287.04,
        "temp_max": 292.04
    },
    "wind": {
        "speed": 7.31,
        "deg": 187.002
    },
    "rain": {
        "3h": 0
    },
    "clouds": {
        "all": 92
    },
    "dt": 1369824698,
    "id": 1851632,
    "name": "Shuzenji",
    "cod": 200
}
Run Code Online (Sandbox Code Playgroud)

我可以很好地调用它,但是如何在"weather"数组中显示"main"和"description"字符串?更具体地说,如何将此信息显示为Toast?

这就是我所拥有的:

protected void onPostExecute(String result){

        try {


            JSONArray weatherArray = new JSONArray(result);
            JSONArray wArray = new JSONArray("weather");

            String mainWeather = wArray.getString(1);
            String mainDescription = wArray.getString(2);

            Toast.makeText(getBaseContext(), mainWeather + " - "
                        + mainDescription,Toast.LENGTH_SHORT).show();

        } catch (Exception e) {
            Log.d("ReadWeatherJSONFeedTask", e.getLocalizedMessage());
        }
Run Code Online (Sandbox Code Playgroud)

因为我正在遵循mobiforge教程,除了这个特定的代码块之外,我没有偏离任何其他地方.

谢谢您的帮助!

编辑: 这里有几个解决方案可以看到@swats和@ user3515851.我选择了@ remees-m-syde,因为它很简单.主要是因为他的解决方案并不要求我通过for循环.

Swa*_*ats 5

我已经使用过,optJSONArray或者 optString代替getJSONArray或者 getString"opt"将返回"",如果该密钥没有值...它不会抛出任何exception类似的情况getString()

试试下面的代码

     JSONObject rootJsonObj = new JSONObject(result);
     JSONArray wArray = rootJsonObj.optJSONArray("weather");
     for (int i = 0; i < wArray.length(); i++) {
          JSONObject weatherJsonObj = wArray.optJSONObject(i);
          String mainWeather = weatherJsonObj.optString("main");
          String mainDescription = weatherJsonObj.optString("description");

          Toast.makeText(getBaseContext(), mainWeather + " - "
                      + mainDescription,Toast.LENGTH_SHORT).show();
     }
Run Code Online (Sandbox Code Playgroud)

有解析问题,你应该从响应结果中取出对象.

编辑:使用optJSONArray或时不需要尝试catch块optString.

  • 我已经使用了optString()方法,你没有..所以在评论之前要仔细检查. (2认同)