6

我试图阻止 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!"}"
}
4

2 回答 2

13

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

@JsonIgnoreProperties(Array("b"))
case class Message(a: String, @JsonProperty("b") b: String)
于 2014-11-27T01:51:39.303 回答
0

jackson-databind 2.8.6和_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"

只有@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)
  }

}
于 2017-01-20T23:50:12.563 回答