json - 使用 json4s 序列化 AnyVal 的序列

标签 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 找到合适的值。 field 。

我注意到 AnyVal 在直接使用时工作正常,但类似于:
case class AnotherModel(id: MyId)

然后我就可以正确地序列化和反序列化。

最佳答案

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

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对于“何时需要分配”部分。

关于json - 使用 json4s 序列化 AnyVal 的序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31344840/

相关文章:

javascript - 将字符串转换为 JSON

scala - 如何在Spark Scala中对具有5个元素的元组的RDD进行排序?

php - 如何将 jQuery 使用 Ajax 生成的输入框传递给 PHP 以插入到 MySQL 中?

javascript - 带有通过 JSON 的超链接的 Google 电子表格

javascript - 循环 JSON 时无法读取未定义的属性 0。

javascript - 如何从 JavaScript 中的 join() 值中仅获取键值?

java - 为什么我不能从 Scala 访问在实现 Java 接口(interface)的类中声明的变量?

scala - Play 2.4.x 中的 Crontab 风格调度?

android - 读/写一个对象到文件

java - 如何在 Android 上高效存储位集