Small Example of Jackson Scala Module?

Here's a complete example:

package com.example.samples

import org.junit.Test
import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.context.annotation.Bean
import java.io.File
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import java.io.StringWriter

class JacksonTest {

  @Test
  @throws[Exception] def jacksonTest(): Unit = {

    //case class Person(var name: String = "", var age: Int = 0)
    //case class Person(@Bean var name: String, @Bean var age: Int)
    case class Person( name: String, age: Int )

    val person = Person("fred", 25)
    val mapper = new ObjectMapper()
    mapper.registerModule(DefaultScalaModule)

    val out = new StringWriter
    mapper.writeValue(out, person)
    val json = out.toString()
    println(json)

    val person2 = mapper.readValue(json, classOf[Person])
    println(person2)
  }
}

However, this fails at mapper.readValue.

Here's my config:

<!-- Jackson libraries for JSON marshalling and unmarshalling -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.2.3</version>
</dependency>

<!-- Jackson module for scala object marshalling and unmarshalling -->
<dependency>
    <groupId>com.fasterxml.jackson.module</groupId>
    <artifactId>jackson-module-scala_2.10</artifactId>
    <version>2.2.2</version>
</dependency>

<!-- Scala Compiler -->
<dependency>
    <groupId>org.scala-lang</groupId>
    <artifactId>scala-compiler</artifactId>
    <version>2.10.2</version>
</dependency>

Any ideas why this fails? I can't see a difference with the working example.


Give this a shot:

val person = Person("fred", 25)
val mapper = new ObjectMapper()
mapper.registerModule(DefaultScalaModule)    

val out = new StringWriter
mapper.writeValue(out, person)
val json = out.toString()
println(json)

val person2 = mapper.readValue(json, classOf[Person])
println(person2)

EDIT

Just be sure to declare the Person class as top level as it will not work otherwise.