Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decoding floating point number in simple.json Java

I am trying to read and parse a json file using simple.json in Java. However, on floating point numbers I get error. How should I parse floating point numbers?

The JSON File is like:

[
  {
    "region":"NF",
    "destination":"d1",
    "source":"s1",
    "time":2003,
    "value":0.1
  },
  {
    "region":"NF",
    "destination":"d2",
    "source":"s2",
    "time":2004,
    "value":0.002
  },
]

My code to parse it is:

JSONArray jsonArray = (JSONArray)obj;
Iterator<JSONObject> iterator = jsonArray.iterator();

while(iterator.hasNext()){
    JSONObject jsonObject = iterator.next();
    String region = (String) jsonObject.get("region");
    String src = (String) jsonObject.get("source");
    String dst = (String) jsonObject.get("destination");
    long time = (long) jsonObject.get("time");
    long val = (long) jsonObject.get("value");
}
like image 398
hAlE Avatar asked Jun 16 '26 14:06

hAlE


2 Answers

If you want to store a floating point number, then you need a variable of that type, i.e., a double.

double val = ((Number)jsonObject.get("value")).doubleValue();

In this case, the get() method should return an instance of java.lang.Number. Then you can call the doubleValue() method to store the floating point value.

like image 190
Joel Avatar answered Jun 19 '26 05:06

Joel


In Java EE 7, use jsonObject.getJsonNumber("key").doubleValue() to get the double value.

See: https://docs.oracle.com/javaee/7/api/javax/json/JsonNumber.html

like image 39
CatSleeping Avatar answered Jun 19 '26 03:06

CatSleeping



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!