How to write Scala Argonaut codec for all Java enums
I have a Scala project that uses a bunch of Java code, for example this Java source:
public enum Category { FOO, BAR };
Then I have a bunch of Scala classes that I serialize to and from JSON using Argonaut like this:
case class Thing (a: String, b: Int, c: Float)
object Thing {
implicit val j = casecodec3 (Thing.apply, Thing.unapply)("a", "b", "c")
implicit val e: Equal[Guild] = Equal.equal (_ == _)
}
Ok, now I want to write a Scala case class that uses Java renaming like so:
case class Thing (a: String, b: Int, c: Float, d: Category)
object Thing {
implicit val j = casecodec4 (Thing.apply, Thing.unapply)("a", "b", "c", "d")
implicit val e: Equal[Guild] = Equal.equal (_ == _)
}
This will result in a compilation error because there is no implicit codec to enumerate the category.
I guess I could write my own codec specifically to work with the Category enumeration by doing something like this:
package object ArgonautImplicits {
implicit val dx: DecodeJson[Category] = StringDecodeJson.map(x => Category.valueOf(x))
implicit val ex: EncodeJson[Category] = EncodeJson(x => jString(x.toString))
}
But I want to know if there is a way to write one codec that will automatically handle any Java enums.
+3
source to share
No one has answered this question yet
Check out similar questions: