Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

jackson - Convert a Map into Scala object

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...