com-lihaoyi / upickle

uPickle: a simple, fast, dependency-free JSON & Binary (MessagePack) serialization library for Scala
https://com-lihaoyi.github.io/upickle
MIT License
722 stars 165 forks source link

Customize upickle to support both null and empty bracket [] as None #568

Closed kaitks closed 4 months ago

kaitks commented 7 months ago

Convert [] as None is the default behavior of upickle, and per document I managed to convert null to None by using an customized upickle

object OptionPickler extends upickle.AttributeTagged {
  override implicit def OptionWriter[T: Writer]: Writer[Option[T]] =
    implicitly[Writer[T]].comap[Option[T]] {
      case None => null.asInstanceOf[T]
      case Some(x) => x
    }

  override implicit def OptionReader[T: Reader]: Reader[Option[T]] = {
    new Reader.Delegate[Any, Option[T]](implicitly[Reader[T]].map(Some(_))){
      override def visitNull(index: Int) = None
    }
  }
}

How to make a custom upickle that can convert both null and [] to None?