Downloaded the JSON library jar file and used pasted
{
"java.project.referencedLibraries": [
"lib/**/*.jar"
]
}
into Preferences: Open Worspace Settings. I;m pretty sure this should work but I still run into “JSON object cannot be resolved” everytime I run my code. Also should I keep my import JSON statement?
Here’s my code:
package JavaFiles;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONObject;
public class Weather {
private static final String API_KEY = "216809c91c7a4c19991121927242405";
private static final String ZIP_CODE = "01773";
private static final String BASE_URL = "http://api.weatherapi.com/v1/current.json";
public static void main(String[] args) {
try {
String urlString = BASE_URL + "?key=" + API_KEY + "&q=" + ZIP_CODE;
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuilder response = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// Parse the JSON response
JSONObject jsonResponse = new JSONObject(response.toString());
JSONObject current = jsonResponse.getJSONObject("current");
// Extract weather information
String tempC = current.getString("temp_c");
String condition = current.getJSONObject("condition").getString("text");
// Display weather information
System.out.println("Current weather in ZIP code " + ZIP_CODE + ":");
System.out.println("Temperature: " + tempC + " °C");
System.out.println("Condition: " + condition);
} else {
System.out.println("GET request failed. Response Code: " + responseCode);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
New contributor
Lady Gaga is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.