简体   繁体   English

将十进制(双精度)值从 JSON 转换为案例类的问题

[英]Issue converting decimal (Double) value from JSON to case class

I am using Scala 2.12 with circe version 0.14.1.我正在使用 Scala 2.12 和 circe 版本 0.14.1。 I am converting a JSON into corresponding case class as below:我正在将 JSON 转换为相应的案例类,如下所示:

case class Document(curr: String, value: Double)
val json = s"""{"Document":{"curr":"USD","value":40000000.01}}"""
import io.circe.generic.auto._
io.circe.parser.decode[Document](json)

The converted case class is below:转换后的案例类如下:

Document(USD,4.000000001E7)

I do not want the Double value to change into a Exponential representation.我不希望 Double 值变为指数表示。 I need it to remain as Double unchanged as我需要它保持 Double 不变

40000000.01 40000000.01

. .

You can override toString implementation to see pain instead of engineering notation:您可以覆盖toString实现以查看痛苦而不是工程符号:

case class Document(curr: String, value: Double) {
  override def toString: String = 
    s"Document($curr,${BigDecimal(value).underlying().toPlainString})"
}

If you want JSON serialization in the plain notation then use the following encoder:如果您想以普通表示法进行 JSON 序列化,请使用以下编码器:

  implicit val doubleE5r: Encoder[Double] = new Encoder[Double] {
    override def apply(a: Double): Json =
      Json.fromJsonNumber(JsonNumber.fromDecimalStringUnsafe(BigDecimal(a).underlying().toPlainString))
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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