-1

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?

1 Answers1

0

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

Gaël J
  • 11,274
  • 4
  • 17
  • 32
  • Thanks @Gaël J DefaultScalaModule on mapper worked locally but when I ran the same on Databricks it throws error. [link](https://stackoverflow.com/questions/68700200/issue-while-converting-scala-map-to-object-on-databricks-notebook) – Sameer Kumar Aug 08 '21 at 11:19