在下面的示例中(scala 2.11和play-json 2.13)
val j ="""{"t":2.2599999999999997868371792719699442386627197265625}"""
println((Json.parse(j) \ "t").as[BigDecimal].compare(BigDecimal("2.2599999999999997868371792719699442386627197265625")))输出为-1。他们不应该是平等的吗?在打印解析后的值时,它会打印舍入值:
println((Json.parse(j) \ "t").as[BigDecimal])给了259999999999999786837179271969944
发布于 2019-03-18 00:02:03
问题是,在默认情况下,play-json会将杰克逊解析器的MathContext设置为DECIMAL128。可以通过将play.json.parser.mathContext系统属性设置为unlimited来修复此问题。例如,在Scala REPL中,如下所示:
scala> System.setProperty("play.json.parser.mathContext", "unlimited")
res0: String = null
scala> val j ="""{"t":2.2599999999999997868371792719699442386627197265625}"""
j: String = {"t":2.2599999999999997868371792719699442386627197265625}
scala> import play.api.libs.json.Json
import play.api.libs.json.Json
scala> val res = (Json.parse(j) \ "t").as[BigDecimal]
res: BigDecimal = 2.2599999999999997868371792719699442386627197265625
scala> val expected = BigDecimal("2.2599999999999997868371792719699442386627197265625")
expected: scala.math.BigDecimal = 2.2599999999999997868371792719699442386627197265625
scala> res.compare(expected)
res1: Int = 0请注意,setProperty应该在引用Json之前首先发生。在正常(非REPL)使用中,您可以通过命令行上的-D或其他方式设置该属性。
或者,您也可以使用Jawn的play-json解析支持,它可以像预期的那样工作:
scala> val j ="""{"t":2.2599999999999997868371792719699442386627197265625}"""
j: String = {"t":2.2599999999999997868371792719699442386627197265625}
scala> import org.typelevel.jawn.support.play.Parser
import org.typelevel.jawn.support.play.Parser
scala> val res = (Parser.parseFromString(j).get \ "t").as[BigDecimal]
res: BigDecimal = 2.2599999999999997868371792719699442386627197265625或者,您可以切换到circe
scala> import io.circe.Decoder, io.circe.jawn.decode
import io.circe.Decoder
import io.circe.jawn.decode
scala> decode(j)(Decoder[BigDecimal].prepare(_.downField("t")))
res0: Either[io.circe.Error,BigDecimal] = Right(2.2599999999999997868371792719699442386627197265625)…在我看来,它比play-json更负责任地处理一系列与数字相关的角落案例。例如:
scala> val big = "1e2147483648"
big: String = 1e2147483648
scala> io.circe.jawn.parse(big)
res0: Either[io.circe.ParsingFailure,io.circe.Json] = Right(1e2147483648)
scala> play.api.libs.json.Json.parse(big)
java.lang.NumberFormatException
at java.math.BigDecimal.<init>(BigDecimal.java:491)
at java.math.BigDecimal.<init>(BigDecimal.java:824)
at scala.math.BigDecimal$.apply(BigDecimal.scala:287)
at play.api.libs.json.jackson.JsValueDeserializer.parseBigDecimal(JacksonJson.scala:146)
...但这超出了这个问题的范围。
老实说,我不确定为什么play-json默认使用MathContext的DECIMAL128,但这是play-json维护者的问题,也超出了本文的讨论范围。
https://stackoverflow.com/questions/55208230
复制相似问题