杰克逊将json反序列化为Seq [Double],但获取Integers而不是Doubles

时间:2018-11-01 12:19:46

标签: json scala jackson deserialization

我想使用Jackson来从json反序列化以获得Seq[Double]。但是可以编辑json并且可以缺少小数点。因此,我想将"list":[1,2.0]反序列化为Seq(1.0,2.0),但是Jackson会给我破碎的清单,其中第一项为Integer,第二项为Double

例外是:

  

java.lang.ClassCastException:无法将java.lang.Integer强制转换为   java.lang.Double at

     

scala.runtime.BoxesRunTime.unboxToDouble(BoxesRunTime.java:114)

我可以告诉杰克逊将字符串"1"读为Double而不是Integer吗?

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.module.SimpleModule
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

case class SomeDoubles(a: Double, list: Seq[Double])

object TestJackson {
  val jacksonMapper = new ObjectMapper() with ScalaObjectMapper
  jacksonMapper.registerModule(new DefaultScalaModule)
  jacksonMapper.registerModule(new SimpleModule)

  def main(args: Array[String]): Unit = {
    val test = SomeDoubles(1.0, Seq(1.0, 2.0))

    println(jacksonMapper.writeValueAsString(test)) // {"a":1.0,"list":[1.0,2.0]}

    val json = """{"a":1,"list":[1,2.0]}""" // changing value 1.0 into 1

    val test2 = jacksonMapper.readValue[SomeDoubles](json) // it deserializes list into Integer and Double
    println(test2) // SomeDoubles(1.0,List(1, 2.0)) ... so the first item in list is already Integer and not Double
    val aValue = test2.a
    println(aValue) // 1.0
    val firstListedValue = test2.list.head
    println(firstListedValue) // Exception in thread "main" java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double
  }
}

2 个答案:

答案 0 :(得分:0)

似乎jakson不能很好地解析ListSeq

根据您的情况,使用Array而不是ListSeq进行以下修改后,代码可以很好地运行:

// line 6: List --> Array
case class SomeDoubles(a: Double, list: Array[Double])

// line 14:
val test = SomeDoubles(1.0, Array(1.0, 2.0))

答案 1 :(得分:0)

我遇到过同样的问题

尝试case class SomeDoubles(a: java.lang.Double, list: Seq[java.lang.Double])

并在反序列化后返回scala Double(如果需要),例如.map(_.toDouble)