'the return value of "org.json.simple.JSONObject.get(Object)" is null even though HTTP request is successful?
So I'm using the Rapid API alpha vantage API to retrieve some stock data. Wrote this code 2 months ago and it successfully printed out the stock price, but when I ran it again today it through this error:
java.lang.NullPointerException: Cannot invoke "java.lang.Double.doubleValue()" because the return value of "org.json.simple.JSONObject.get(Object)" is null
I tried the testing the endpoint on RapidAPI's API playground, which worked. Then I tried calling the json without requesting a specific address and the json was retrieved successfully (Pic of what the json response looks like) It just seems that issues crop up when I call this:
double price = (Double) jsonObject.get("05. price");
Here is my code. I censored my API key and stuff:
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.json.JSONArray;
import org.json.simple.JSONValue;
import org.json.simple.JSONObject;
public static void main(String[] args) {
try{
Helper.requestPrice();
} catch(Exception e){
e.printStackTrace();
}
}
public static void requestPrice() throws Exception{
OkHttpClient client = new OkHttpClient();
String ticker = "msft";
Request request = new Request.Builder()
.url("https://alpha-vantage.p.rapidapi.com/query?function=GLOBAL_QUOTE&symbol="+ticker+"&datatype=json")
.get()
.addHeader("x-rapidapi-host", "alpha-vantage.p.rapidapi.com")
.addHeader("x-rapidapi-key", "xxxxxxx")
.build();
Response response = client.newCall(request).execute();
String myData = response.body().string();//works
Object obj = JSONValue.parse(myData); //works
JSONObject jsonObject = (JSONObject) obj; //works
double price = (Double) jsonObject.get("05. price");
System.out.println(price);
}
Thank you!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
