Small Example of Jackson Scala Module?

41,410

Solution 1

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.

Solution 2

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.

Share:
41,410
Greg
Author by

Greg

Updated on May 16, 2020

Comments

  • Greg
    Greg almost 4 years

    Can anyone point me towards a simple example of Jackson serialization/deserialization with their Scala module for 2.10? I'm looking for reflection-based JSON not requiring field-by-field annotation or assignment and it seemed this could do that, but their documentation includes no examples.

    If I have a case class:

    case class Person(name:String, age:Int)
    val person = Person("Fred", 65)
    

    So from their github readme:

    val mapper = new ObjectMapper()
    mapper.registerModule(DefaultScalaModule)
    

    OK, now what...? How to I convert p to/from JSON?