How do i serialize a sealed abstract class with Json4s in Scala?
The following classes are defined:
sealed abstract class Person extends Product with Serializable
case class Spouse(name: String, age: Int) extends Person
case class Customer(name: String, age: Int, spouse: Spouse) extends Person
I create an object of type Customer:
val customer: Customer = Customer("Joe", 35, Spouse("Marilyn", 33))
Then I serialize to JSON:
implicit val formats = DefaultFormats
val serialized = write(customer)
That works fine. But then I try to deserialize:
val parsedObj = Serialization.read[Person](serialized)
Here I keep getting error:
org.json4s.package$MappingException: Parsed JSON values do not match with class constructor
I spent a lot of time trying to make this work...
After a lot of googling around and a close read of the Json4s documentation i found out that I need a custom Serializer to make it work.
However, it took me a while to figure out that I need to set the formats to actually use the custom Serializer.
Here is the code that works for me.
Simple Example:
Custom Serializer:
Output