iva*_*one 1 json scala playframework
我有两个从同一个父代继承的类。我想在父级中拥有一个通用的JSON读取器,该读取器将根据提供的JSON返回合适的子级。在下面的示例代码片段中更容易解释这一点;
import play.api.libs.json.{JsPath, JsonValidationError, Reads}
sealed abstract class Animal(sound: String)
case class Goat(hooves: String) extends Animal("meh")
case class Cat(needsMilk: Boolean) extends Animal("meow")
val json ="""{"type": "goat", "hooves": "All good for climbing trees"}"""
object Animal {
val isSupportedAnimal: Reads[String] =
Reads.StringReads.filter(JsonValidationError("Unsupported animal"))(str => {
List("goat", "cat").contains(str)
})
val animalReads: Reads[Animal] = ((JsPath \ "type").read[String](isSupportedAnimal) and
//if animal is cat, use the cat specific reads and return a cat object
//if animal is goat, use goat specific reads and return a goat
)()
}
Run Code Online (Sandbox Code Playgroud)
给定json代码段中的,我想要have Goat对象,因为指定的类型为goat。
我是scala的新手,所以我可能以错误的方式来解决问题。欢迎提出建议。
使用Map:
sealed abstract class Animal(val sound: String) // You probably want a val here, btw
final case class Goat(hooves: String) extends Animal("meh")
final case class Cat(needsMilk: Boolean) extends Animal("meow")
object Animal {
val readers: Map[String, Reads[_ <: Animal]] = Map(
"goat" -> implicitly[Reads[Goat]],
"cat" -> implicitly[Reads[Cat]],
// Sidenote: Trailing commas ^ make future modification easy
)
// Bonus: Set[String] <: String => Boolean, so you get isSupportedAnimal for free
// val isSupportedAnimal: String => Boolean = readers.keys
implicit val animalReads: Reads[Animal] = new Reads[Animal] {
def reads(s: JsValue): JsResult[Animal] = {
val tpe = (s \ "type").as[String]
val read = readers.get(tpe)
read.map(_.reads(s)).getOrElse(JsError(s"Unsupported animal: $tpe"))
}
}
}
Run Code Online (Sandbox Code Playgroud)
如果您不希望有此样板,可以查看此库(使用无形状)。
| 归档时间: |
|
| 查看次数: |
485 次 |
| 最近记录: |