kPieczonka
kPieczonka

Reputation: 404

Parsing response from Api - Data returned is seen as double and Integer - How to Parse

The API returns either a whole number like = 129 or A decimal for example 0.28 Here is the response from API:

"ETH":{"USD":730.06}"

I'm trying to parse the JSON with the following:

Double ethPrice = (double) arr.get("USD");

Which works if the data returned is a number with a decimal but if it is a whole number then I'm getting:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double

I'm not doing any mathematical function with the response, therefore, a string type would work too.

I feel like it is a small problem I should have solved already. But spent a bit of time on it now and don't want to waste anymore. Any help would be great.

Edit :

Request code snippet of parsing:

JSONObject obj = new JSONObject(result);
JSONObject arr = obj.getJSONObject("ETH");
Double ethPrice = (double) arr.get("USD");

Where result is a string (inside async task - onPostExecute(String result))

Upvotes: 1

Views: 441

Answers (1)

Denysole
Denysole

Reputation: 4051

If you sure that you will get Double, you can use arr.getDouble("USD") instead of arr.get("USD").

Your code will be the next:

JSONObject obj = new JSONObject(result);
JSONObject arr = obj.getJSONObject("ETH");
Double ethPrice = arr.getDouble("USD");

Upvotes: 2

Related Questions