So I have a wierd issue. Im connecting to a websocket.
Everything is fine as the data flows in.
@Override
public void onMessage(WebSocket webSocket, String text)
{
// My data looks like
// {"Type":3, "F":[1,2,3974.909912109375,27500,1639207185]}
obj = new JSONObject(text);
// Then I get the array in "F" key
o = obj.getJSONArray("F");
// I want to now cast these variables into variables to use.
// So I do...
Integer v = (Integer) o.get(0);
Integer t = (Integer) o.get(1);
// This works fine.
// If I stop here.....
// the websocket stays connected, and keeps streaming....
// However.... if I do this....
Double p = (Double) o.get(2);
// The websocket crashes, and disconnects??
// Program continues running though and there is no exceptions.
// Its merely disconnecting the socket for some reason, by casting?
}
What is going on here?? Why cant I cast that to a double??
Ive also tried Float with no luck.
Any ideas??
Iva also tried...
Double p = new Double((Integer) o.get(2));
Double p = new Double((Float) o.get(2));
Float p = (Float) o.get(2);
float p = (float) o.get(2);
double p = Double.parseDouble((String) o.get(2));
All these things crash/disconnect the websocket.
Seems when I try to access index 2, things go wonky.
However....
I can do
System.out.println(o.get(2));
Just fine, and it prints
3974.909912109375
CodePudding user response:
You can't cast that to a Double
directly. Instead try using
Double p = Double.parseDouble(o.get(2));
That being said, it would probably be a better thing to keep your data consistent and cast everything to Double
while you're at it to avoid issues down the line.
String text = "1,2,3974.909912109375,27500,1639207185";
String[] inputs = text.split(",");
List<Double> doubles = Arrays.stream(inputs)
.map(Double::parseDouble)
.collect(Collectors.toList());