在 simple.json Java 中解码浮点数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21690413/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 10:04:58  来源:igfitidea点击:

Decoding floating point number in simple.json Java

javajsonjson-simple

提问by hAlE

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?

我正在尝试使用 Java 中的 simple.json 读取和解析 json 文件。但是,在浮点数上我得到错误。我应该如何解析浮点数?

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

回答by maerics

I would guess that this library (I'm guessing it's json-simplefrom your tag) returns numeric types as type double.

我猜这个库(我猜它是json-simple从你的标签中)返回数字类型作为 type 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

回答by Joel

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.

在这种情况下,该get()方法应该返回java.lang.Number 的一个实例。然后就可以调用该doubleValue()方法来存储浮点值。

回答by CatSleeping

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

在 Java EE 7 中,用于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