I’ve got some JSON that I need to parse, and my project already uses Play, so that seems like the right place to start.
Given these definitions:
sealed trait Thing
case class Foo(i: Int) extends Thing
case class Bar(s: String, t: List[Thing]) extends Thing
I would want this JSON:
{
s: "doomy doomy doom",
t: [ 24, { s: "doooom!", t: [ 1, 2, 3 ] }, 42, 126 ]
}
To become this object:
Bar("doomy doomy doom", List(Foo(24), Bar("doooom!", List(Foo(1), Foo(2), Foo(3))), Foo(42), Foo(126)))
Any suggestions?
2
Answers
Try to define custom codecs for the trait (without discriminator) and lazy codecs for the recursive type
Scala play json nested cyclic dependency json parsing
To add to @dmytro-mitin answer, you can use Scala’s value class for
Foo
. Play JSON documentation includes Reads/Writes/Formats for value classes. Then you can useInt
instead of an object with single field in your original example. Here is an updated example with a value class: