Jackson Scala模块的小例子?

时间:2013-06-06 15:56:29

标签: json scala jackson

有人能指出一个简单的Jackson序列化/反序列化示例,他们的Scala模块是2.10吗?我正在寻找基于反射的JSON,不需要逐个字段的注释或赋值,它似乎可以做到这一点,但它们的文档中没有包含任何示例。

如果我有一个案例类:

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

所以从他们的github自述文件:

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

好的,现在是什么......?如何将p转换为/从JSON转换?

3 个答案:

答案 0 :(得分:36)

试一试:

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)

修改

请确保将Person类声明为顶级,否则将无效。

答案 1 :(得分:8)

这是一个完整的例子:

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)
  }
}

但是,这在mapper.readValue中失败了。

这是我的配置:

<!-- 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>

为什么会失败的任何想法?我看不出与工作示例的区别。

答案 2 :(得分:-1)

我创建了一个通用函数来转换JSON String to Case Class/ObjectCase Class/Object to JSON String

build.sbt文件中需要的SBT依赖关系:

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到案例类/对象的字符串

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
      }
    }
  }

将类/对象转换为JSON字符串

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
      }
    }
  }