When working with UUIDs in Scala using json4s, you might run into issues serializing and deserializing UUID objects by default. Json4s does not handle java.util.UUID
out-of-the-box. Fortunately, there’s a simple and elegant solution using JavaTypesSerializers
.
To enable UUID support in json4s, you can add JavaTypesSerializers.all
to your implicit formats:
implicit lazy val formats: Formats =
Serialization.formats(NoTypeHints) ++ JavaTypesSerializers.all
val user = User(UUID.randomUUID(), "John Doe")
val jsonString = Serialization.write(user)
println(jsonString)
When working with Java types like UUID, JavaTypesSerializers.all
is the most straightforward way to extend Json4s support. It’s a clean, idiomatic, and minimal solution — no need to write custom serializers manually.
Why formats
Are Needed in Json4s?
In json4s, formats
are essential because they tell the library how to convert between Scala objects and JSON — this includes:
- Serialization (object → JSON)
- Deserialization (JSON → object)
Formats includes Type hints, Custom serializers (e.g., for UUID
, Date
, etc.) and Information on how to map case class fields
Without formats
, json4s doesn’t know how to handle non-primitive types.