[英]Decoding floating point number in simple.json Java
I am trying to read and parse a json file using simple.json in Java. 我正在尝试使用Java中的simple.json读取和解析json文件。 However, on floating point numbers I get error.
但是,在浮点数上我会出错。 How should I parse floating point numbers?
我应该如何解析浮点数?
The JSON File is like: JSON文件类似于:
[
{
"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, ie, a double. 如果要存储浮点数,则需要该类型的变量,即双精度型。
double val = ((Number)jsonObject.get("value")).doubleValue();
In this case, the get()
method should return an instance of java.lang.Number . 在这种情况下,
get()
方法应返回java.lang.Number的实例。 Then you can call the doubleValue()
method to store the floating point value. 然后,您可以调用
doubleValue()
方法来存储浮点值。
I would guess that this library (I'm guessing it's json-simple from your tag) returns numeric types as type double
. 我猜想这个库(我想从您的标签中它是json-simple )返回数字类型为
double
类型。
Double value = (Double) jsonObject.get("value");
For example (tested and working with json-simple-1.1.1): 例如(经过测试并使用json-simple-1.1.1):
String jsonString = "{\"foo\":1.23}";
JSONObject obj = (JSONObject) JSONValue.parse(jsonString);
Double d = (Double) obj.get("foo"); // => 1.23
In Java EE 7, use jsonObject.getJsonNumber("key").doubleValue()
to get the double value. 在Java EE 7中,使用
jsonObject.getJsonNumber("key").doubleValue()
获得双jsonObject.getJsonNumber("key").doubleValue()
值。
See: https://docs.oracle.com/javaee/7/api/javax/json/JsonNumber.html 参见: https : //docs.oracle.com/javaee/7/api/javax/json/JsonNumber.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.