无法在json数组中打印json对象

时间:2018-10-11 17:23:34

标签: java json

这是我正在使用的json。我需要打印description数组内的weather对象。编译时出现JSONArray[2] not found异常。我正在使用java-json。

{
  "coord": {
    "lon": 72.85,
    "lat": 19.01
  },
  "weather": [
    {
      "id": 721,
      "main": "Haze",
      "description": "haze",
      "icon": "50n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 303.15,
    "pressure": 1009,
    "humidity": 74,
    "temp_min": 303.15,
    "temp_max": 303.15
  },
  "visibility": 3000,
  "wind": {
    "speed": 2.1,
    "deg": 360
  },
  "clouds": {
    "all": 20
  },
  "dt": 1539273600,
  "sys": {
    "type": 1,
    "id": 7761,
    "message": 0.0642,
    "country": "IN",
    "sunrise": 1539219701,
    "sunset": 1539262109
  },
  "id": 1275339,
  "name": "Mumbai",
  "cod": 200
}

这是代码-

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
import org.json.JSONArray;

class Send_HTTP_Request2 {
    public static void main(String[] args) {
     try {
         Send_HTTP_Request2.call_me();
        } catch (Exception e) {
         e.printStackTrace();
       }
     }

 static void call_me() throws Exception {
     String url = "http://api.openweathermap.org/data/2.5/weather?id=1275339&APPID=77056fb4e0ba03b117487193c37c90d2";
     URL obj = new URL(url);
     HttpURLConnection con = (HttpURLConnection) obj.openConnection();

     int responseCode = con.getResponseCode();
     System.out.println("\nSending 'GET' request to URL : " + url);

     BufferedReader in = new BufferedReader(
             new InputStreamReader(con.getInputStream()));
     String inputLine;
     StringBuffer response = new StringBuffer();
     while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
     }
     in.close();

     JSONObject myResponse = new JSONObject(response.toString());
         JSONArray jrr= myResponse.getJSONArray("weather");
          System.out.println("CITY-"+myResponse.getString("name"));
         JSONObject desc = jrr.getJSONObject(2);

         System.out.println(desc);
}
}

1 个答案:

答案 0 :(得分:0)

对于getJSONObject(int index)Link to the Javadoc here)的JSONArray方法

您正确地在数组内部获取了JSONObject,但是您获取了错误的索引,在这种情况下,索引为0,因为在Java中,索引0是数组的第一项。 (More on Arrays and indexes here

然后,您只需调用desc.getString("description")并将其分配给String即可,因为描述码是String类型。

因此,更具体地说,您可以进行一些链接(假设我们不检查null或使用for循环或其他方法遍历数组):

JSONObject myResponse = new JSONObject(response.toString());
JSONArray jrr= myResponse.getJSONArray("weather");
System.out.println("CITY-"+myResponse.getString("name"));
JSONObject weatherObj = jrr.getJSONObject(0);
String desc = weatherObj.getString("description");
System.out.println(desc);

希望这会有所帮助!
编辑格式