scala - Serialize to JSON a list of case classes having common trait -
let's have
trait t case class a(s: string) extends t case class b(s: string, i: int) extends t i need able serialize list[t]
after declaring
implicit val awrites = json.writes[a] implicit val bwrites = json.writes[b] i seek
val list = list(a("1"), b("2", 2)) json.tojson(list) but compiler says
no json serializer found type t. seek implement implicit writes or format type.
my solutions is
implicit val twrites = new writes[t] { def writes(t: t) = t match { case a: => json.tojson(a) case b: b => json.tojson(b) } } i don't it, because requires alter twrite each new class extending t.
is there more flexible implementation?
the json.writes macro requires unapply method, cannot utilize trait. if could, serialize parameters knows t. solution best can do, although (depending on utilize case) have add together parameter distinguishes between , b when deserializing.
by way, having extend matches when add together new type mutual problem (see expression problem). should create trait sealed compiler inform when pattern match statement misses newly added type.
json scala playframework-2.0 case-class
No comments:
Post a Comment