Use the OpenWeatherMap API to fetch weather data for a city based on its ZIP code and write the weather data to a file.
weather_data.json
file.
public class WeatherDataExercise {
public static void main(String[] args) {
// OpenWeatherMap API key (replace with your own API key)
String apiKey = "";
// Step 1: Ask the user for a 5-digit ZIP code
// Step 2: Fetch weather data from the API
String apiUrl = "https://api.openweathermap.org/data/2.5/weather?zip=" "
// Step 3: Write the weather data to a file
// Step 4: Read back the JSON file and display its content
}
}
Enter a 5-digit ZIP code: 21114 Weather data written to file successfully! Reading back the JSON file... Contents of weather_data.json: { "coord": { "lon": -76.6802, "lat": 39.0112 }, "weather": [ { "id": 800, "main": "Clear", "description": "clear sky", "icon": "01d" } ], "base": "stations", "main": { "temp": 278.41, "feels_like": 275.9, "temp_min": 277.46, "temp_max": 279.71, "pressure": 1024, "humidity": 42, "sea_level": 1024, "grnd_level": 1019 }, "visibility": 10000, "wind": { "speed": 3.09, "deg": 280 }, "clouds": { "all": 0 }, "dt": 1740325720, "sys": { "type": 2, "id": 2002307, "country": "US", "sunrise": 1740311258, "sunset": 1740351168 }, "timezone": -18000, "id": 0, "name": "Crofton", "cod": 200 }