0

I'm currently on json4s 3.2.10. I realize json4s is buggy and shouldn't be used for anything ever, but this is a legacy codebase and switching out the json parser is impractical currently.

I have a situation where json fields that don't exist (and are optional arrays) are deserialized into classes that have Option[Seq[SomeClass]] as Some(List()) instead of None. This is a known major bug in Json4s that hasn't been resolved in almost two years:

https://github.com/json4s/json4s/issues/198

The other bug comments mention custom workarounds, but don't go into details. I'm trying to write a customer deserializer to deal with this, but I'm a little confused by the syntax and what I should be doing. I started in with the following:

import org.json4s.{Formats, Serializer, TypeInfo, _}

class JsonSequenceOption[A] extends Serializer[Option[Seq[A]]] {

  val Class = classOf[Option[Seq[A]]]

  override def deserialize(implicit format: Formats)  = {
    case (TypeInfo(Class, _), seqJson) => {
      //???
    }
  }

  override def serialize(implicit format: Formats) = {
    case (seq : Option[Seq[A]]) => seq match {
      case Some(a : Seq[A]) => JArray(a.map(x => JString(x.toString)).toList)
      case None => JNothing
    }
  }
}

..but I'm not sure exactly what to do near the ???. Am I even going down the right path? Is there a more straightforward solution?

djsumdog
  • 2,560
  • 1
  • 29
  • 55

1 Answers1

0

I found I didn't need a custom serializer. Since this project uses a custom marshaller, an easy solution is to replace extractOpt[A] with extract[Seq[Option[A]]].

Change:

(someobject \ "someField").extractOpt[Seq[String]]

To:

(someobject \ "someField").extract[Option[Seq[String]]]
djsumdog
  • 2,560
  • 1
  • 29
  • 55