使用json4s序列化AnyVal的序列

时间:2015-07-10 15:37:36

标签: json scala serialization deserialization json4s

尝试使用scala中的json4s序列化AnyVal序列时遇到问题。

以下是使用FunSuite进行的测试,可以重现问题:

  import org.json4s._
  import org.json4s.jackson.JsonMethods._
  import org.json4s.jackson.Serialization._
  import org.scalatest.{FunSuite, Matchers}

  case class MyId(id: String) extends AnyVal

  case class MyModel(ids: Seq[MyId])

  class AnyValTest extends FunSuite with Matchers {

    test("should serialize correctly") {

      implicit val formats = DefaultFormats

      val model = MyModel(Seq(MyId("1"), MyId("2")))
      val text = write(model)

      parse(text).extract[MyModel] shouldBe model
    }
  }

尝试从JValue中提取MyModel时测试失败,因为它无法为ids字段找到合适的值。

我注意到AnyVal在直接使用时工作正常,但是:

case class AnotherModel(id: MyId)

然后我能够正确地序列化和反序列化。

1 个答案:

答案 0 :(得分:0)

我知道这个问题已经有一年了,但我遇到了同样的问题。写下我做了什么,以防它帮助其他人。您将需要一个自定义序列化器。

case class Id(asString: String) extends AnyVal

class NotificationSerializer extends CustomSerializer[Id](format ⇒ (
  {case JString(s) => Id(s)},
  {case Id(s) => JString(s)}))

如果没有上面的序列化,您的JSON将类似于

{"ids":[[{"asString":"testId1"},{"asString":"testId2"}]]}

我不完全确定为什么AnyVal案例类序列化在它是另一个案例类的一部分时工作正常但不是独立的。我最好的猜测是,行为是由于JVM对包含值类的数组的分配行为。有关“何时需要分配”部分,请参阅http://docs.scala-lang.org/overviews/core/value-classes.html