I've got a JSON with a list of events :
[
{"id":"1","kind":"start"},
{"id":"2","kind":"start"},
{"id":"1","kind":"stop"},
{"id":"4","kind":"start"},
{"id":"4","kind":"stop"}
]I encoded them as an ADT :
sealed trait Event {
val kind: String
}
case class Start(id: String) extends Event {
val kind = "start"
}
case class Stop(id: String) extends Event {
val kind = "stop"
}How to decode them ?
I tried with json4s :
import org.json4s._
import org.json4s.jackson.JsonMethods._
import org.scalatest.{FunSpec, Matchers}
import org.json4s.DefaultFormats
sealed trait Event {
val kind: String
}
case class Start(id: String) extends Event {
val kind = "start"
}
case class Stop(id: String) extends Event {
val kind = "stop"
}
class Main extends FunSpec with Matchers {
it("json4s") {
implicit val formats = DefaultFormats
def decode(json: String): List[Event] = parse(json).extract[List[Event]]
val json =
"""[
| {"id":"1","kind":"start"},
| {"id":"2","kind":"start"},
| {"id":"1","kind":"stop"},
| {"id":"4","kind":"start"},
| {"id":"4","kind":"stop"}
|]
""".stripMargin
println("result: "+decode(json))
true shouldBe true
}
}But I got :
No constructor for type Event, JObject(List((id,JString(1)), (kind,JString(start))))
org.json4s.package$MappingException: No constructor for type Event, JObject(List((id,JString(1)), (kind,JString(start))))
Any ideas ?
So, the solution I found (thanks Loïc Descotte) was using play-json with play-json-derived-codecs
Here is my final code :