这是我正在使用的 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 回答
吃鸡游戏
TA贡献1829条经验 获得超7个赞
对于getJSONObject(int index)(此处链接到 Javadoc)的 JSONArray 方法
获取数组内的 JSONObject 是正确的,但是获取了错误的索引,在本例中为 0,因为在 Java 中,索引 0 是数组的第一项。(更多关于数组和索引在这里)
然后您只需调用desc.getString("description")并将其分配给一个字符串,因为描述键是一个字符串类型。
所以更具体地说,你会做一些链接这个(假设我们没有检查空值或使用 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);
希望这可以帮助!
添加回答
举报
0/150
提交
取消