public static String getWeatherOnTomorrow(Double latitude, Double longitude) throws…
- User
public static String getWeatherOnTomorrow(Double latitude, Double longitude) throws IOException, InterruptedException { String tomorrow = LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ofPattern("YYYY-MM-dd"));
HttpClient client = HttpClient.newHttpClient(); HttpRequest request = HttpRequest.newBuilder().uri(URI.create( String.format("https://api.open-meteo.com/v1/forecast?latitude=%s&longitude=%s&daily=weather_code,temperature_2m_max,temperature_2m_min&start_date=%s&end_date=%s", latitude, longitude, tomorrow, tomorrow))) .build(); HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); client.close(); Utils utils = new Utils(); String responceText = response.body(); Gson gson = new Gson(); Map<String, Object> map = gson.fromJson(responceText, new TypeToken<Map<String, Object>>() { }.getType()); System.out.println(map); LinkedTreeMap<String, Object> daily = (LinkedTreeMap<String, Object>) map.get("daily"); String wmo = utils.getWMOWeatherByCode((Integer) daily.get("weather_code")); String tempMin = daily.get("temperature_2m_min").toString(); String tempMax = daily.get("temperature_2m_max").toString();// System.out.println(wmo); System.out.println(tempMin); System.out.println(tempMax);
return null; }Exception in thread "main" java.lang.ClassCastException: class java.util.ArrayList cannot be cast to class java.lang.Integer (java.util.ArrayList and java.lang.Integer are in module java.base of loader 'bootstrap') at org.example.api.ApiMain.getWeatherOnTomorrow(ApiMain.java:72) at org.example.Main.main(Main.java:13)
- Assistant
The error you're facing is due to trying to cast an
ArrayListto anIntegerin this line:String wmo = utils.getWMOWeatherByCode((Integer) daily.get("weather_code"));The
weather_codevalue in the JSON response is most likely a collection (list or array) rather than a single integer. This isn't unusual for weather data APIs, where daily forecasts could include lists of values for each day.Here's how to fix this:
-
Inspect the API Response Structure: Check that the structure matches your expectations. It sounds like
weather_codeis an array or list of codes rather than a single code. -
Parse the Array: Parse
weather_codeas a list and then decide how you want to handle multiple codes (if there are multiple):
List<Double> weatherCodes = (List<Double>) daily.get("weather_code"); for (Double code : weatherCodes) { String wmo = utils.getWMOWeatherByCode(code.intValue()); System.out.println(wmo); }Note: This assumes
weather_codeis a list of doubles (as JSON numbers may be interpreted as doubles by default). Adjust the list element type as needed.Remember to add error handling if the array is empty or not formatted as expected. Also, this approach assumes each code can be independently processed using
utils.getWMOWeatherByCode(). -