jsonscalamessagepack

How do you convert a case class to a class?


I have a case class Person(name:String, id:Int) for serialization reasons (MessagePack), I need to convert this to a class. Is there an easy / elegant way to do this which does not require too much boilerplate or creation?

case class Person(name:String, id:Int) -> class Person(name:String, id:Int)


Solution

  • A case class can be serialized as a "normal" class as it is de facto a normal class. As it makes all constructor arguments accessable by default it's an even better fit for serialisation than a normal class.

    The case class just tells the compiler to automatically add some methods as equals and hashCode to the class. At the same time there is a companion object with an apply method added, but this doesn't affect the normal class at all.

    So if there arise problems with Serialization the chance is quite hight that the source of the problem lies elsewhere.

    You could try json4s https://github.com/json4s/json4s to convert your case class to JSON and then convert it to the MessagePack format.

    import org.json4s._
    import org.json4s.native.Serialization
    import org.json4s.native.Serialization.{read, write}
    implicit val formats = Serialization.formats(ShortTypeHints(List(classOf[Person])
    val jsonString : String = write(Person("Andi", 42))
    
    // convert with MessagePack as you would do with normal JSON