Search code examples
jsonscalaplayframeworkplay-json

How to write implicit Writes for case class having more than 22 fields


case class Foo(
  _1:Int,_2:Int,_3:Int,_4:Int,_5:Int,
  _21:Int,_22:Int,_23:Int,_24:Int,_25:Int,
  _31:Int,_32:Int,_33:Int,_34:Int,_35:Int,
  _41:Int,_42:Int,_43:Int,_44:Int,_45:Int,
  _51:Int,_52:Int,_53:Int,_54:Int,_55:Int
)

For a case class like this, I need to write implicit json de- / serializer. I tried splitting the fields, and had a JSONFormat. But still I need implicit OWrited for using Json.obj(). I tried with play-json-extensions also. Any ideas?


Solution

  • There's really 3 avenues for you to explore here:

    1. Write out each class explicitly yourself (yes, tons of boilerplate.)
    2. Do it with Macros or Shapeless.
    3. Use someone's library who already did #2.

    I like it when someone else does the work for me. So with that in mind, #3 seems like my preferred solution... And what would you know? Someone else did just that: play-json-derived-codecs. Since it uses Shapeless, it will be able to handle case classses of arbitrary size, not just those constrained by ProductN (1-22, depending on your version of Scala.)