@JsonIgnore serialising Scala case class property using Jackon and Json4s

筅森魡賤 提交于 2019-12-04 07:57:50

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)

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

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!