Combining type and field serializers

前端 未结 2 1003
刺人心
刺人心 2021-01-04 08:06

Let\'s assume I have a case class with the following setup:

case class Place(id:java.util.UUID, name:String)

I can write a (working!) seria

2条回答
  •  北荒
    北荒 (楼主)
    2021-01-04 08:27

    The trick is to not write a serializer for your type, but for the type that you're using inside (in this case java.util.UUID)

    Then you can add that serializer to the toolbox and from then any type using UUID will work exactly like types using DefaultSerializer supported fields did:

    case object UUIDSerialiser extends CustomSerializer[UUID](format => (
        {
          case JString(s) => UUID.fromString(s)
          case JNull => null
        },
        {
          case x: UUID => JString(x.toString)
        }
      )
    )
    
    implicit val json4sFormats = Serialization.formats(NoTypeHints) + UUIDSerialiser
    

    Update link to the PR

    Update 2 the PR was merged, and now, in case of UUID you can use:

    import org.json4s.ext.JavaTypesSerializers
    
    implicit val json4sFormats = Serialization.formats(NoTypeHints) ++ JavaTypesSerializers.all
    

提交回复
热议问题