@JsonIgnore serialising Scala case class property

2020-07-10 10:38发布

问题:

I'm trying to prevent one of the properties of a Scala case class being serialised. I've tried annotating the property in question with the usual @JsonIgnore and I've also tried attaching the @JsonIgnoreProperties(Array("property_name")) to the case class. Neither of which seem to achieve what I want.

Here's a small example:

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

回答1:

Change your @JsonIgnore to @JsonProperty("b"). You have correctly stated to Ignore the property 'b but 'b has not yet been annotated as a property.

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


回答2:

With jackson-databind 2.8.6 and jackson-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"

Only @JsonIgnoreProperties works fine,

Example case class as below where I'm ignoring "eventOffset" and "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
  }
}

test

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

}