尝试在 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/