Decoding floating point number in simple.json Java

hAlE picture hAlE · Feb 11, 2014 · Viewed 15.8k times · Source

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");
}

Answer

Joel picture Joel · Feb 11, 2014

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.