@JsonIgnore使用Jackson和Json4s序列化Scala案例类属性

时间:2014-09-03 22:48:32

标签: scala jackson json4s

我正在尝试阻止Scala case class的某个属性被序列化。我尝试使用通常的@JsonIgnore对相关媒体进行注释,我也尝试将@JsonIgnoreProperties(Array("property_name"))附加到case class。这两者似乎都达不到我想要的。

这是一个小例子:

import org.json4s._
import org.json4s.jackson._
import org.json4s.jackson.Serialization
import org.json4s.jackson.Serialization.{read, write}
import com.fasterxml.jackson.annotation._

object Example extends App {

    @JsonIgnoreProperties(Array("b"))
    case class Message(a: String, @JsonIgnore b: String)

    implicit val formats = Serialization.formats(NoTypeHints)
    val jsonInput = """{ "a": "Hello", "b":"World!" }"""
    val message = read[Message](jsonInput)
    println("Read " + message) // "Read Message(Hello,World!)

    val output = write(message) 
    println("Wrote " + output) // "Wrote {"a":"Hello","b":"World!"}"
}

2 个答案:

答案 0 :(得分:12)

将@JsonIgnore更改为@JsonProperty(“b”)。您已正确声明忽略该属性'b但是'b尚未注释为属性。

@JsonIgnoreProperties(Array("b"))
case class Message(a: String, @JsonProperty("b") b: String)

答案 1 :(得分:0)

使用jackson-databind 2.8.6jackson-module-scala 2.8.4

"com.fasterxml.jackson.core" % "jackson-databind" % "2.8.6",
"com.fasterxml.jackson.module" % "jackson-module-scala_2.11" % "2.8.4"

只有@JsonIgnoreProperties正常,

示例案例类如下所示,我忽略了"eventOffset""hashValue"

import java.util.Date

import com.fasterxml.jackson.annotation.{JsonIgnore, JsonIgnoreProperties}
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.module.scala.DefaultScalaModule
import com.fasterxml.jackson.module.scala.experimental.ScalaObjectMapper

@JsonIgnoreProperties(Array("eventOffset", "hashValue"))
case class TestHappenedEvent(eventOffset: Long, hashValue: Long, eventType: String,
                             createdDate: Date, testField: String) {

  def this() {
    this(0, 0, "", new Date(), "")
  }

  def toJSON(): String = {
    val objectMapper = new ObjectMapper() with ScalaObjectMapper
    objectMapper.registerModule(DefaultScalaModule)

    val data = this.copy()
    val stream = new ByteArrayOutputStream()
    objectMapper.writeValue(stream, data)
    stream.toString
  }
}

测试

import org.scalatest.FunSuite
import spray.json._

class BaseEventSpecs extends FunSuite {

  val abstractEvent = TestHappenedEvent(0, 1, "TestHappenedEvent", new Date(2017, 10, 28), "item is sold")

  test("converts itself to JSON") {

    assert(abstractEvent.toJSON().parseJson ==
      """
        {
          "eventType":"TestHappenedEvent",
          "createdDate":61470000000000,
          "testField":"item is sold"
        }
      """.stripMargin.parseJson)
  }

}