[英]Parsing decimal numbers, some of which lack a decimal separator, in JSON data using JSON-Simple (Java)
I am trying to use the JSON-Simple JSON processor library.我正在尝试使用JSON-Simple JSON 处理器库。
When parsing JSON fragment such as:解析 JSON 片段时如:
"speed":1.13
…I call get
and cast as a Double
. …我调用
get
并作为Double
。 No problem.没问题。
Double speed = ( Double ) wind.get( "speed" );
But then I encounter a value without a decimal fraction.但后来我遇到一个没有小数的值。 Ex:
1
rather than 1.0
.例如:
1
而不是1.0
。
"speed":1
Granted, the publisher of this data should have written "speed":1.0
.当然,这个数据的发布者应该写
"speed":1.0
。 But they did not.但他们没有。
My get
with casting throws an exception:我的
get
with cast 抛出异常:
Exception in thread "main" java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.lang.Double (java.lang.Long and java.lang.Double are in module java.base of loader 'bootstrap')
Exception in thread "main" java.lang.ClassCastException: class java.lang.Long cannot be cast to class java.lang.Double (java.lang.Long and java.lang.Double are in module java.base of loader 'bootstrap ')
Apparently JSON-Simple insisted on parsing the JSON value of 1
as a Long
.显然JSON-Simple坚持将 JSON 值
1
解析为Long
。 So I need a workaround, a way to tell JSON-Simple how to parse this particular element.所以我需要一个解决方法,一种告诉JSON-Simple如何解析这个特定元素的方法。
➥ Is there a way to tell JSON-Simple to parse the string inputs as Double
regardless of whether a decimal separator (a decimal point) is present? ➥ 有没有办法告诉 JSON-Simple 将字符串输入解析为
Double
而不管是否存在小数分隔符(小数点)?
➥ Even better, can I tell JSON-Simple to parse the string input for a particular JSON element as BigDecimal
to bypass the inaccuracy of floating-point ? ➥ 更好的是,我可以告诉 JSON-Simple 将特定 JSON 元素的字符串输入解析为
BigDecimal
以绕过浮点的不准确性吗? (that is, going from String
to BigDecimal
without involving floating-point along the way) (也就是说,从
String
到BigDecimal
的过程中不涉及浮点)
Instead of casting try而不是铸造尝试
Double.parseDouble(wind.get( "speed" ).toString())
You are using the original JSON-Simple library led by Fang Yidong.您使用的是方一东领导的原始 JSON-Simple 库。 Later versions 2 and 3 were developed as a fork at this Clifton Labs page on GitHub, led by Davin Loegering.
后来的版本 2 和 3 是在 Davin Loegering 领导的Clifton Labs 页面上 GitHub 上的一个分支开发的。
The original does not support BigDecimal
.原版不支持
BigDecimal
。 The fork does supports BigDecimal
.叉子确实支持
BigDecimal
。 See the getBigDecimal
method.请参阅
getBigDecimal
方法。
The fork has changed the original library quite a bit.叉子对原始库进行了相当大的更改。 See the History section of that Clifton Labs page .
请参阅Clifton Labs 页面的“历史”部分。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.