Small Example of Jackson Scala Module?

前端 未结 3 1727
轮回少年
轮回少年 2020-12-05 06:34

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

相关标签:
3条回答
  • 2020-12-05 07:23

    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.

    0 讨论(0)
  • 2020-12-05 07:30

    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.

    0 讨论(0)
  • 2020-12-05 07:36

    I have created a generic function to convert JSON String to Case Class/Object and Case Class/Object to JSON String.

    SBT Dependencies required in build.sbt file:

    name := "jackson-example"
    
    scalaVersion := "2.12.11"
    
    libraryDependencies += "com.fasterxml.jackson.module" %% "jackson-module-scala" % "2.10.1"
    libraryDependencies += "com.fasterxml.jackson.core" % "jackson-databind" % "2.10.1"
    

    JSON String to Case Class/Object

    def fromJson[T](json: String)(implicit m: Manifest[T]): Option[T] = {
        Try {
          lazy val mapper = new ObjectMapper() with ScalaObjectMapper
          mapper.registerModule(DefaultScalaModule)
          mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
          mapper.readValue[T](json)
        } match {
          case Success(x) => Some(x)
          case Failure(err) => {
            logger.error("@@@@Got " + err.getMessage() + " while JSON to Object:--> " + json)
            None
          }
        }
      }
    

    Case Class/Object to JSON String

    def toJson[T](obj: T)(implicit m: Manifest[T]): Option[String] = {
        Try {
          lazy val mapper = new ObjectMapper() with ScalaObjectMapper
          mapper.registerModule(DefaultScalaModule)
          mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
          mapper.writeValueAsString(obj)
        } match {
          case Success(x) => Some(x)
          case Failure (err) => {
            logger.error("@@@@Got " + err.getMessage() + " while converting object  to JSON:--> " + obj)
            None
          }
        }
      }
    
    0 讨论(0)
提交回复
热议问题