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");
}
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With