Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

With reference to [Stackoverflow] Scala: convert map to case class I tried to replicate one of the response and I see the following error:

Cannot construct instance of 'com.practice.scala.Test' (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator) at [Source: UNKNOWN; line: -1, column: -1]

Code:

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.ScalaObjectMapper

case class Test(k1: Int, k2: String, k3: String)

object Workspace {
  def fromMap[T](map: Map[String, Any])(implicit m: Manifest[T]): T = {
    val mapper = new ObjectMapper() with ScalaObjectMapper
    mapper.convertValue(map)
  }

  def main(args: Array[String]): Unit = {
    val myMap = Map("k1" -> 1, "k2" -> "val2", "k3" -> "val3")
    val result = fromMap[Test](myMap)
    println(result)
  }
}

What does this error says? Am I missing anything?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
168 views
Welcome To Ask or Share your Answers For Others

1 Answer

You need to register the DefaultScalaModule on your mapper:

// With 2.10 and later
val mapper = JsonMapper.builder()
  .addModule(DefaultScalaModule)
  .build()

// versions before 2.10 (also support for later 2.x but not 3.0)
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)

Source: https://github.com/FasterXML/jackson-module-scala#usage


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...