Combining type and field serializers

风格不统一 提交于 2019-11-30 17:44:05

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

There is now a UUID serializer provided in the extras package of json4s. It will most likely be available in version 3.2.11 (which has not been released as of this writing).

You'll be able to do something like this:

import org.json4s.ext.JavaTypesSerializers

implicit val json4sFormats = Serialization.formats(NoTypeHints) ++ JavaTypesSerializers.all

This was taken from the tests for this feature's PR.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!