The ClassCastException you're encountering occurs because the JSON fields you're trying to cast (weather_code, temperature_2m_max, and temperature_2m_min) are being parsed as ArrayList (i.e., List<Object>) rather than single Integer or Double values. This happens because the API returns these fields as lists, even if you're requesting data for a single day.
Here's how you can fix the issue:
-
Handle the List Structure:
Since the API returns lists for daily data, you need to extract the first (and presumably only) element from these lists.
-
Correct Date Formatting:
Additionally, there is a minor issue with the date format. You should use yyyy instead of YYYY to represent the calendar year.
-
Remove Unnecessary client.close():
The HttpClient in Java 11 doesn't have a close() method because it's intended to be reused and managed by the JVM. Removing this line will prevent potential errors.
Here's the corrected version of your method:
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.gson.internal.LinkedTreeMap;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
public static String getWeatherOnTomorrow(Double latitude, Double longitude) throws IOException, InterruptedException {
// Use LocalDate instead of LocalDateTime since we're dealing with dates, not date-times
String tomorrow = LocalDate.now().plusDays(1).format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
HttpClient client = HttpClient.newHttpClient();
String url = 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
);
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
// No need to close the client
// Parse the JSON response
String responseText = response.body();
Gson gson = new Gson();
Map<String, Object> map = gson.fromJson(responseText, new TypeToken<Map<String, Object>>() {}.getType());
// Debugging output
System.out.println(map);
// Extract the "daily" data
LinkedTreeMap<String, Object> daily = (LinkedTreeMap<String, Object>) map.get("daily");
Utils utils = new Utils();
// Since the fields are lists, extract the first element
List<Double> weatherCodeList = (List<Double>) daily.get("weather_code");
List<Double> tempMinList = (List<Double>) daily.get("temperature_2m_min");
List<Double> tempMaxList = (List<Double>) daily.get("temperature_2m_max");
if (weatherCodeList.isEmpty() || tempMinList.isEmpty() || tempMaxList.isEmpty()) {
throw new IllegalStateException("No weather data available for the specified date.");
}
// Assuming you have a single entry for tomorrow
Integer weatherCode = weatherCodeList.get(0).intValue();
String wmo = utils.getWMOWeatherByCode(weatherCode);
String tempMin = String.valueOf(tempMinList.get(0));
String tempMax = String.valueOf(tempMaxList.get(0));
// Debugging output
System.out.println("Weather Code: " + wmo);
System.out.println("Temperature Min: " + tempMin);
System.out.println("Temperature Max: " + tempMax);
// You can format and return the weather information as needed
return String.format("Weather: %s, Min Temp: %s°C, Max Temp: %s°C", wmo, tempMin, tempMax);
}
Breakdown of the Changes:
-
Date Formatting:
- Changed
LocalDateTime to LocalDate since we're only dealing with dates.
- Corrected the date format pattern from
"YYYY-MM-dd" to "yyyy-MM-dd".
-
Handling Lists:
- Cast the daily fields (
weather_code, temperature_2m_min, temperature_2m_max) to List<Double> instead of attempting to cast them directly to Integer or String.
- Extracted the first element from each list since you're requesting data for a single day.
-
Removed client.close():
- Removed
client.close(); because HttpClient doesn't have a close method and is designed to be reused.
-
Error Handling:
- Added a check to ensure that the lists are not empty to prevent
IndexOutOfBoundsException.
-
Return Value:
- Modified the return statement to provide a meaningful string containing the weather information. You can adjust this as needed based on how you want to use the data.
Additional Recommendations:
-
Type Safety:
For better type safety and to avoid unchecked casts, consider defining a proper Java class that matches the JSON structure and use Gson to deserialize directly into that class.
-
Error Handling:
Implement more robust error handling, such as checking the HTTP response status code and handling cases where the API might return an error message.
-
Utility Methods:
Ensure that your Utils.getWMOWeatherByCode method can handle the Integer input correctly and returns a meaningful description of the weather code.
By making these adjustments, your method should correctly parse the API response and avoid the ClassCastException.