0

Sorry if the question is a bit simple. I am new to this and i am currently trying to fetch some values using a websites API. I will drop a link below. Here is the issue. The code i have is the exact code the website provided. I want to take the "quote" values only from the result sent from them. Here is the code:

import java.net.URI;
import java.io.IOException;
import java.lang.InterruptedException;
import javax.websocket.*;

@ClientEndpoint
public class WSClient  {

@OnOpen
public void onOpen(Session session) throws java.io.IOException
{
    session.getBasicRemote().sendText("{\"ticks\": \"R_100\"}");
}

@OnMessage
public void onMessage(String message)
{
    System.out.println("ticks update: " + message);
}

public static void main(String[] args)
    throws IOException, DeploymentException, InterruptedException
{
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();
    URI apiUri = URI.create("wss://ws.binaryws.com/websockets/v3");
    Session session = container.connectToServer(WSClient.class, apiUri);
    Thread.sleep(3000);
}
}

And here is the result on my Console in eclipse:

ticks update: {"echo_req":{"ticks":"R_100"},"tick":{"epoch":"1461413058","symbol":"R_100","quote":"37673.45","id":"810945BC-094B-11E6-B438-8E7300DB46A6"},"msg_type":"tick"}

The results works fine but i want to take just the "quote" Value which is a numeric value.

Here is the link to their API Website / Dev Website: https://developers.binary.com/

Thank you in Advance :)

1 Answers1

0

Your response looks like a JSON string you should just do this

@OnMessage
public void onMessage(String message)
    JSONObject response = new JSONObject(message);
    int quote = Integer.parseInt(response.getString("quote"));
}
  • And where in the code should i put this? Like i mentioned, i am very new when it comes to understanding API. Specially java – user3380047 Apr 23 '16 at 12:17
  • You should replace your line in onMessage with this. You'll need to import org.json.JSONObject for this to work. Replace myAPIresponse in my code with the message variable you have – Akshay Shenoy Apr 23 '16 at 12:20
  • Here is the issue. "Cannot make a static reference to the non-static method getString(String) from the type JSONObject" The code is "(JSONObject.getString("quote"));" That is the error i am getting now – user3380047 Apr 23 '16 at 12:26
  • Sorry I made a really silly mistake. I have edited my code. It shouldn't be JSONObject.getString, it should be response.getString – Akshay Shenoy Apr 23 '16 at 12:31
  • So finally it asked for a throws declaration to work and so i did. but now it gives me a list of errors. org.glassfish.tyrus.core.AnnotatedEndpoint onError INFO: Unhandled exception in endpoint WSClient. org.json.JSONException: JSONObject["quote"] not found. And other errors – user3380047 Apr 23 '16 at 12:40