Extracting lift-json into a case class with an upper bound

匆匆过客 提交于 2019-12-03 14:20:00

Extracting parameterized case class is not yet supported. One workaround (not sure if this works for your case though) is to make Fruits a concrete type and add the type information into JSON.

import net.liftweb.json._
import net.liftweb.json.Extraction._
import net.liftweb.json.JsonAST._
import net.liftweb.json.Printer._

abstract class MyObjects
case class Apple(id: Int, name: String, color: String) extends MyObjects
case class Orange(id: Long, name: String, state: String) extends MyObjects

case class Fruits(aisle: Int, bin: Int, hasWhat: Option[List[MyObjects]])

object Test extends Application {
  // This configuration adds an extra field for MyObjects to JSON
  // which tells the real type of a MyObject.
  implicit val formats = Serialization.formats(FullTypeHints(List(classOf[MyObjects])))

  val fs = Fruits(0, 0, Some(List(
    Apple(1, "Granny Smith", "green"), 
    Apple(2, "Grenade", "red"))))
  val json = decompose(fs)
  println(pretty(render(json)))

  assert (json.extract[Fruits] == fs)
}

That prints:

{
  "aisle":0,
  "bin":0,
  "hasWhat":[{
    "jsonClass":"Apple",
    "id":1,
    "name":"Granny Smith",
    "color":"green"
  },{
    "jsonClass":"Apple",
    "id":2,
    "name":"Grenade",
    "color":"red"
  }]
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!