简体   繁体   English

使用 JSON-Simple (Java) 在 JSON 数据中解析十进制数字,其中一些缺少小数分隔符

[英]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) (也就是说,从StringBigDecimal的过程中不涉及浮点)

Instead of casting try而不是铸造尝试

Double.parseDouble(wind.get( "speed" ).toString())

Use later version使用更高版本

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM