Serializing AnyVal sequences using json4s

I have a problem trying to serialize AnyVal sequences using json4s in scala.

Here is a test using FunSuite that reproduces the problem:

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

The test does not work when trying to retrieve MyModel from JValue, because it cannot find a suitable value for the field ids.

I notice that AnyVal works fine when used directly, but with something like:

case class AnotherModel(id: MyId)

Then I can serialize and deserialize correctly.

+4
source share
1 answer

I know this question is one year old, but I ran into the same problem. Writing what I did if it helps someone else. You will need a special serializer.

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"}]]}

, case AnyVal , case, . , JVM , . . http://docs.scala-lang.org/overviews/core/value-classes.html " ".

0

All Articles