使用JSON-Simple(Java)在JSON数据中解析十进制数字(其中有些缺少十进制分隔符) [英] Parsing decimal numbers, some of which lack a decimal separator, in JSON data using JSON-Simple (Java)

查看:242
本文介绍了使用JSON-Simple(Java)在JSON数据中解析十进制数字(其中有些缺少十进制分隔符)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JSON-简单 JSON处理器库.

解析JSON片段时,例如:

 "speed":1.13
 

…我叫get并转换为Double.没问题.

 Double speed = ( Double ) wind.get( "speed" );
 

但是随后我遇到一个不带小数部分的值.例如:1而不是1.0.

 "speed":1
 

当然,此数据的发布者应写成"speed":1.0.但是他们没有.

我的get进行强制转换会抛出异常:

线程"main"中的异常java.lang.ClassCastException:无法将类java.lang.Long强制转换为类java.lang.Double(java.lang.Long和java.lang.Double在以下模块的java.base中:加载程序'bootstrap')

显然, JSON-Simple 坚持将1的JSON值解析为Long.因此,我需要一种变通方法,一种告诉 JSON-Simple 如何解析此特定元素的方法.

➥是否有一种方法可以告诉JSON-Simple将字符串输入解析为Double,而不管是否浮点数不准确 >? (也就是说,从StringBigDecimal而不涉及沿途的浮点数)

解决方案

使用更高版本

您正在使用由方益东(Fang Yidong)领导的原始JSON-Simple库.更高版本2和3是在GitHub上的此Clifton Labs页面上作为分叉开发的,戴文·洛厄林(Davin Loegering)

原件不支持BigDecimal. 分叉确实支持BigDecimal.请参见 getBigDecimal 方法.

fork极大地改变了原始库.请参阅 Clifton Labs页面历史部分.

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)

解决方案

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.

这篇关于使用JSON-Simple(Java)在JSON数据中解析十进制数字(其中有些缺少十进制分隔符)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆