Parsing decimal numbers, some of which lack a decimal separator, in JSON data using JSON-Simple (Java)

会有一股神秘感。 提交于 2019-12-11 08:17:06

问题


I am trying to use the JSON-Simple JSON processor library.

When parsing JSON fragment such as:

"speed":1.13

…I call get and cast as a 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.

"speed":1

Granted, the publisher of this data should have written "speed":1.0. But they did not.

My get with casting throws an exception:

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. So I need a workaround, a way to tell JSON-Simple how to parse this particular element.

➥ 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?

➥ 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? (that is, going from String to BigDecimal without involving floating-point along the way)


回答1:


Use later version

You are using the original JSON-Simple library led by Fang Yidong. Later versions 2 and 3 were developed as a fork at this Clifton Labs page on GitHub, led by Davin Loegering.

The original does not support BigDecimal. The fork does supports BigDecimal. See the getBigDecimal method.

The fork has changed the original library quite a bit. See the History section of that Clifton Labs page.




回答2:


Instead of casting try

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



来源:https://stackoverflow.com/questions/58964542/parsing-decimal-numbers-some-of-which-lack-a-decimal-separator-in-json-data-us

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!