I would like to pass some values i have from a string in to double variables. the string output looks like this:
{
"high":"1635.07",
"last":"1635.07",
"timestamp":"1489299397",
"volume":"321.34139374",
"vwap":"1602.72987907",
"low":"1595.03",
"ask":"1635.89",
"bid":"1605.10"
}
I just want this data to be like:
double high = (value of high in string);
double last = (value of last in string);
ect...
Im having trouble as java throws an error I believe because of the mix of words and numbers.
Thanks in advance for the help.
code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JOptionPane;
public class btc {
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception {
btc http = new btc();
http.sendGet();
}
// HTTP GET request
private void sendGet() throws Exception {
String url = "https://api.quadrigacx.com/v2/ticker?book=btc_cad";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
// optional default is GET
con.setRequestMethod("GET");
//add request header
con.setRequestProperty("User-Agent", USER_AGENT);
System.out.println("\nSending 'GET' request to URL : " + url);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
//write to variables
String test = response.toString();
//double high = test("high");
//Double high = Double.parseDouble(test);
System.out.println(test);
//print result
//JOptionPane.showMessageDialog(null, response.toString());
}
}
As already mentioned in the comments what you receiving from the server is a JSON object as documented in QuadrigaCX's API description so it should be parsed as such as the order of the members may vary aswell as the whitespace.
What's interesting about this JSON string is that all values are actually strings as they are enclosed in double quotation marks. But these strings contain values that can be interpreted and parsed as double.
Using minimal-json, which is a minimalistic Java library that allows you to parse JSON and access contained values directly. The following code makes use of it and "reads" high and last as double values:
JsonObject jsonObject = Json.parse(responseBody).asObject();
double high = Double.parseDouble(jsonObject.get("high").asString());
double last = Double.parseDouble(jsonObject.get("last").asString());
Here responseBody corresponds to what you have named test in your sendGet method and is the response from the web server as one string.
Related
I am trying to make a program which would exchange a given currency into a different one using live exchange rate.
This is how I get data from exchangeratesapi.io:
URL url = new URL("https://api.exchangeratesapi.io/latest?symbols=USD,GBP");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
System.out.println(inputLine);
}
The code returns what is the current exchange rate ({"rates":{"USD":1.1029,"GBP":0.84183},"base":"EUR","date":"2020-01-30"}), but I dont how to get that 1.1029 into an equation.
The "base" is the Euro. If you look on their github page here you will see in the README it says "Rates are quoted against the Euro by default. Quote against a different currency by setting the base parameter in your request." So what that means is if you put in 100, it's looking at the rate of 100 Euro. So to find another value it would be:
Amount * Exchange Rate = value for that Symbol
So in that example of 100 euro:
100 * 1.1029 = $110.29 USD.
EDIT: An update based on your comment. Here is how you would get the value, using the org.json library that you can find here.
public static void main(String[] args) throws ParseException {
String jsonString = "{ \"rates\" : { \"USD\" : 1.1029, \"GBP\" : 0.84183 }, \"base\" : \"EUR\", \"date\" : \"2020-01-30\" }";
double rate = getExchangeRate(jsonString);
System.out.println(rate);
}
public static double getExchangeRate(String jsonInput) {
JSONObject object = new JSONObject(jsonInput);
double rate = object.getJSONObject("rates").getDouble("USD");
return rate;
}
Output:
1.1029
If you're new to using this sort of stuff and JSON confuses you, I suggest you read up on some tutorials on how it works. A good start would be here.
I hope this helps!
Use the JSONObject-import:
import org.json.JSONObject;
Small change to your code in the last few lines:
URL url = new URL("https://api.exchangeratesapi.io/latest?symbols=USD,GBP");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("GET");
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String jsonText = readAll(in);
JSONObject yourData = new JSONObject(jsonText);
This is readAll:
private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}
After that your data is a JSONObject and you can get the requested value like this:
double yourRate = yourData.getJSONObject("rates").getDouble("USD");
class Rate {
public double USD;
public double GBP;
}
class RateContainer{
public Rate rates;
public String base;
public String date;
}
in your gradle file:
dependencies {
implementation 'com.google.code.gson:gson:2.8.6'
}
Gson gson = Gson();
RateContainer container = gson.fromJson(inputLine,RateContainer.class);
Systen.out.println(container.rates.USD + "");
I am new to JSON data format and java programming language; hence, I cannot find a valid answer. Actually, I have to read this API https://www.doviz.com/api/v1/currencies/all/latest, and obtain some important contents from this API. Hence, I decided to use google's GSON class, and I wrote this code.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.Scanner;
import com.google.gson.Gson;
public class Main {
public static void main( String[] args ) throws Exception{
String line = "";
String jsonString = "";
URL myUrl = new URL("https://www.doviz.com/api/v1/currencies/all/latest");
BufferedReader reader = new BufferedReader( new InputStreamReader(myUrl.openStream()) );
while( (line = reader.readLine()) != null ){
System.out.println(line);
jsonString += line;
}
reader.close();
jsonString = jsonString.substring(1, jsonString.length() - 1);
Gson gson = new Gson();
Currency json = gson.fromJson(jsonString, Currency.class);
}
}
public class Currency {
public double getSelling(){
return selling;
}
public double getBuyiing(){
return buying;
}
public String getCode(){
return code;
}
private double selling;
private transient long update_date;
private transient int currency;
private double buying;
private transient double change_rate;
private transient String name;
private transient String full_name;
private String code;
}
This code causes error, and as far as I guess, the main reason for the errors is that I do not put backslash in son string like this: "{\"brand\":\"Jeep\", \"doors\": 3}"
What I am wondering is why we need to put these backslash ?
There are 2 things to mention.
The " character is the String delimiter. A String starts at a " mark, and ends at the next one. (When initializing it explicitly, not using other variables) If you want to include " character in your String, you need to escape it like \" - so Java knows that it is not the end of the String, just a part of the content.
In JSON you should use single quotes ' - many libraries accept double quotes also, but it is not correct actually, and if any api complains about them, the API is right.
So your payload should look like {'brand': 'Jeep', 'doors': 3} I mean the other way around of course.
When you receive a JSON output from the api, you can directly use the output and can deserialize it. You don't need to have escape characters in the json string. They are required when you define the json string yourself. For example String s = "{\"current_user_url\"}"; because it is the compiler which forces you to escape it. But the json output you are getting as an API response is in a variable and if type of variable and the content you are assigning to it are same then compiler can't compain about that.
Now, I have used your code only but used the Github public API and I am able to deserialize the output json without any operation on the output string whatsoever like escaping the "" or changing "" to ''.
class Github {
private String current_user_url;
private String authorizations_url;
public String getCurrent_user_url() {
return current_user_url;
}
public void setCurrent_user_url(String current_user_url) {
this.current_user_url = current_user_url;
}
public String getAuthorizations_url() {
return authorizations_url;
}
public void setAuthorizations_url(String authorizations_url) {
this.authorizations_url = authorizations_url;
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
String line = "";
String jsonString = "";
URL myUrl = new URL("https://api.github.com");
BufferedReader reader = new BufferedReader( new InputStreamReader(myUrl.openStream()) );
while( (line = reader.readLine()) != null ){
//System.out.println(line);
jsonString += line;
}
reader.close();
System.out.println(jsonString);
Gson g = new Gson();
Github gi = g.fromJson(jsonString, Github.class);
System.out.println(gi.getAuthorizations_url());
System.out.println(gi.getCurrent_user_url());
}
I also defined the json string myself and desrialized it using GSON. In this case while defining the json string I needed to escape the double quotes as shown below:
String s = "{\"current_user_url\":\"http://test.com/user\"}";
Gson g = new Gson();
Github gi = g.fromJson(s, Github.class);
System.out.println(gi.getCurrent_user_url());
Also, JSON strings should contain double quotes only and if you use single quotes then you may get an error.
I am running this program just fine :
package cse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class cse {
public static void main(String[] args) throws Exception {
String key = "My API KEY";
String qry = "Test";
if(qry.contains(" ")) {
qry = qry.replace(' ', '+');
System.out.println("here");
System.out.println(qry);
}
URL url = new URL("https://www.googleapis.com/customsearch/v1?key="+key+ "&cx=MY_CUSTOM SEARCH&q="+qry+"&alt=json");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
BufferedReader br = new BufferedReader(new InputStreamReader(
(conn.getInputStream())));
String output;
System.out.println("Output from Server .... \n");
while ((output = br.readLine()) != null) {
if(output.contains("\"link\": \"")) {
String link = output.substring(output.indexOf("\"link\": \"")+("\"link\": \"").length(), output.indexOf("\","));
System.out.println(link); //Will print the google search links
}
}
conn.disconnect();
}
}
Now what I want to do is have it only return the one result, and add this result to a string array. I could even just grab the first result and put it in there if that would be easier but I'm just not sure how to go about this.
So basically, if I searched the same query three times, the array would consist of [http://www.speedtest.net/,http://www.speedtest.net/,http://www.speedtest.net/]
Thanks in advance for any help, which would be much appreciated!
If you want to sort the data (ascending or descending) use a Query. The Table doesn't have any order. Even the Fields don't have any relevant order.
I'm learning Java, so I decided to toy around with the GW2 with the hope of coding something useful: API:http://wiki.guildwars2.com/wiki/API:Main
I'm trying to get the following data: https://api.guildwars2.com/v1/world_names.json
into a Java String, this is my code:
public static void main(String[] args) {
URL url = null;
String jsonData = "";
try {
url = new URL("https://api.guildwars2.com/v1/world_names.json");
InputStream is = url.openStream();
Scanner scan = new Scanner(is);
while(scan.hasNext()) {
jsonData += scan.next();
}
scan.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(jsonData);
}
The problem is I'm losing the format of the Strings (I'm missing the blank characters that separate words).
This is what you see if you access the URL:
[{"id":"1009","name":"Fort Aspenwood"},
{"id":"1005","name":"Maguuma"}, {"id":"1008","name":"Jade Quarry"},
This is what I get in my String:
{"id":"1009","name":"FortAspenwood"}, {"id":"1005","name":"Maguuma"},
{"id":"1008","name":"JadeQuarry"}
How can I fix that? am I doing something wrong?
My final goal is to convert this data to an object, and then be able to ask for an specific ID or NAME to the api and get more data, such as maps or events, but first things first, since I'm learning and I can't get the String right..
Thank you for reading,
Right from the documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
You don't want any sort of tokenization, so you can borrow a one-liner from Stupid Scanner tricks:
final String jsonData = new Scanner(is).useDelimiter("\\A").next();
which consumes the entire input stream in one line.
N.B. if you do stick with using a loop, you should use a StringBuilder instead of concatenation (jsonData += scan.next();) because that operation has quadratic asymptotic runtime.
However, I strongly recommend that you use Jackson for all your real-world JSON processing uses.
One way to approach this problem is to use a library, like Jackson, that knows how to parse json input. Here is an example program that goes out to the url you provided and creates a List of DataTransferObject.
This code depends on http://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl/1.9.13
This is not strictly speaking the answer to your question but is another approach.
package stackoverflow;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import java.io.IOException;
import java.net.URL;
import java.util.List;
public class JsonParser {
private static final String urlString = "https://api.guildwars2.com/v1/world_names.json";
public static void main(String[] args) throws IOException {
JsonParser parser = new JsonParser();
URL url = new URL(urlString);
ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(url.openStream());
List<DataTransferObject> dtoList = mapper.readValue(root, new TypeReference<List<DataTransferObject>>(){});
for(DataTransferObject dto : dtoList) {
System.out.println("DTO: " + dto);
}
}
public static class DataTransferObject {
public int id;
public String name;
#Override
public String toString() {
return "ID: " + id + " NAME: " + name;
}
}
}
As I can see you are doing:
while(scan.hasNext()) {
jsonData += scan.next();
}
next() returns the next token which is separated by spaces, new lines etc. Now since you have to get the whole line from your JSON data, you can do:
while(scan.hasNextLine()) {
jsonData += scan.nextLine();
}
How do I create a Java program that enters the words "Hello World" into Google and then retrieves the html from the results page? I'm not trying to use the Robot class.
URL url = new URL("http://www.google.com/search?q=hello+world");
url.openStream(); // returns an InputStream which you can read with e.g. a BufferedReader
If you make repeated programmatic requests to Google in this way they will start to redirect you to "we're sorry but you look like a robot" pages pretty quick.
What you may be better doing is using Google's custom search api.
For performing google search through a program, you will need a developer api key and a custom search engine id. You can get the developer api key and custom search engine id from below urls.
https://cloud.google.com/console/project'>Google Developers Console
https://www.google.com/cse/all'>Google Custom Search
After you got the both the key and id use it in below program. Change apiKey and customSearchEngineKey with your keys.
For step by step information please visit - http://www.basicsbehind.com/google-search-programmatically/
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class CustomGoogleSearch {
final static String apiKey = "AIzaSyAFmFdHiFK783aSsdbq3lWQDL7uOSbnD-QnCnGbY";
final static String customSearchEngineKey = "00070362344324199532843:wkrTYvnft8ma";
final static String searchURL = "https://www.googleapis.com/customsearch/v1?";
public static String search(String pUrl) {
try {
URL url = new URL(pUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = br.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String buildSearchString(String searchString, int start, int numOfResults) {
String toSearch = searchURL + "key=" + apiKey + "&cx=" + customSearchEngineKey + "&q=";
// replace spaces in the search query with +
String newSearchString = searchString.replace(" ", "%20");
toSearch += newSearchString;
// specify response format as json
toSearch += "&alt=json";
// specify starting result number
toSearch += "&start=" + start;
// specify the number of results you need from the starting position
toSearch += "&num=" + numOfResults;
System.out.println("Seacrh URL: " + toSearch);
return toSearch;
}
public static void main(String[] args) throws Exception {
String url = buildSearchString("BasicsBehind", 1, 10);
String result = search(url);
System.out.println(result);
}
}