Json对象不在Java中显示

时间:2017-10-17 12:53:27

标签: java json

我想从JSONObject获取“天气”数据,但这个错误即将来临。

org.json.JSONException: JSONObject["weather"] not a string.
    at org.json.JSONObject.getString(JSONObject.java:639)
    at GetWeather.main(GetWeather.java:49)

这是我的代码

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class GetWeather {       

    public static String getWeather(String args){
        String result =" ";
        URL url ;
        HttpURLConnection urlConnection = null;
        try{
            url = new URL(args);
            urlConnection = (HttpURLConnection) url.openConnection();
            InputStream in = urlConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data= reader.read();
            while(data!=-1){
                char current=(char) data;
                result += current;
                data= reader.read();
            }
            return result;
        }catch(MalformedURLException e){
             e.printStackTrace();
        } catch (IOException e) { 
            e.printStackTrace();
        }
        return null;
    }

    //main
    public static void main(String[] args){
        String s1 = getWeather(args[0]);
        try {
            JSONObject jsonObject = new JSONObject(s1);
            String weather= jsonObject.getString("weather");
            System.out.println(weather);
        } catch (JSONException e) { 
            e.printStackTrace();
        }
    }
}

这是我传递的字符串

http://api.openweathermap.org/data/2.5/weather?q=Delhi&APPID=04b767167643ea6af521695e7948e0fb

这是我回来的数据

{"coord":{"lon":77.22,"lat":28.67},"weather":[{"id":721,"main":"Haze","description":"haze","icon":"50d"}],"base":"stations","main":{"temp":305.86,"pressure":1007,"humidity":38,"temp_min":304.15,"temp_max":307.15},"visibility":3500,"wind":{"speed":1.5,"deg":320},"clouds":{"all":0},"dt":1508241600,"sys":{"type":1,"id":7808,"message":0.0051,"country":"IN","sunrise":1508201604,"sunset":1508242734},"id":1273294,"name":"Delhi","cod":200}

在格式化版本中看起来像

{
    "coord": {
        "lon": 77.22,
        "lat": 28.67
    },
    "weather": [{
            "id": 721,
            "main": "Haze",
            "description": "haze",
            "icon": "50d"
        }
    ],
    "base": "stations",
    "main": {
        "temp": 305.86,
        "pressure": 1007,
        "humidity": 38,
        "temp_min": 304.15,
        "temp_max": 307.15
    },
    "visibility": 3500,
    "wind": {
        "speed": 1.5,
        "deg": 320
    },
    "clouds": {
        "all": 0
    },
    "dt": 1508241600,
    "sys": {
        "type": 1,
        "id": 7808,
        "message": 0.0051,
        "country": "IN",
        "sunrise": 1508201604,
        "sunset": 1508242734
    },
    "id": 1273294,
    "name": "Delhi",
    "cod": 200
}

请告诉我我的代码有什么问题以及该怎么做。

1 个答案:

答案 0 :(得分:1)

"天气"的价值您尝试获取的不是String,而是JSONArray

要阅读其中的所有信息,请尝试使用getJSONArray()

try {
    JSONObject jsonObject = new JSONObject(s1);
    // read the `weather` content
    JSONArray weatherArray = jsonObject.getJSONArray("weather");
    // get only the first element of `weather`, the only one existing
    JSONObject weatherObject = (JSONObject)weatherArray.get(0);
    // read all its' properties
    for (Object key : weatherObject.keySet()) {
        System.out.println("key:" + key + ", value: " + weatherObject.get((String)key));
    }
} catch (JSONException e) {
    e.printStackTrace();
}

其他信息,例如" temp"或者"压力",只需使用getJSONObject(),因为" main"有JSONObject类型:

 JSONObject mainObject = jsonObject.getJSONObject("main");
 System.out.println("pressure value: " + mainObject.get("pressure"));
 System.out.println("temp value: " + mainObject.get("temp"));