首页 > 解决方案 > Play JSON Reads:读取值,可以多种类型呈现

问题描述

我有这样的JSON ship

{
  "name" : "Watership Elizbeth",
  "sea": "white",
  "size": 100500,
  "residents" : [ {
    "type" : "men",
    "age" : 4,
    "sex": 0
  }, {
    "type" : "cat",
    "legs" :4,
    "color" : "black",
    "leg1" :{
      "color" : "black"
    },
    "leg2" :{
      "color" : "white"
    },
    "leg3" :{
      "color" : "brown"
    },
    "leg4" :{
      "color" : "black"
    }
  },{
    "type" : "bird",
    "size" : "XXL",
    "name": "ostrich"
  }, {"type": "water",...}, {"type": "mice",...}, {...}]
}

正如您在 JsArray 中看到的,residents我有不同的居民:men, cat, bird, ... water,... 所有居民ship在 Scala 代码中都有自己的简单案例类:

case class Men (type: String, age: Int, sex: Int)
case class Leg (color: String)
case class Cat (type: String, legs: Int, color: String, leg1: Leg, leg2: Leg, leg3: Leg, leg4: Leg)
case class Bird (...)

同样对于每个简单的案例类,我都写readers在它们的伴随对象中:

object Men {
implicit val reads: Reads[Ship] = (
    (JsPath \ "type").read[String] and
      (JsPath \ "age").read[Int] and
      (JsPath \ "sex").read[Int]
    )(Ship.apply _)
}
// and so on for another objects...

我没有找到如何为其创建案例类的主要Ship问题reads

case class Ship (name: String, sea: String, size: Int, residents: Seq[???])

object Ship {
implicit val reads: Reads[Ship] = (
    (JsPath \ "name").read[String] and
      (JsPath \ "sea").read[String] and
      (JsPath \ "size").read[Int] and
      (JsPath \ "residents").read[Seq[???]]
    )(Ship.apply _)
}

如您所见residents,数组中的元素可以是不同的类型:Men, Cat, Bird.. 我想改为???读取Ship我的类型的所有对象或类似 `AnyVal 的对象,但它不起作用:

// for case classes
case class Ship (name: String, sea: String, size: Int, residents: Seq[Man,Cat,Bird,...])
case class Ship (name: String, sea: String, size: Int, residents: Seq[AnyVal])

// for case reads
(JsPath \ "residents").read[Seq[Man,Cat,Bird,...]]
(JsPath \ "residents").read[Seq[AnyVal]]

如何编写可以读取其关键多种类型的案例类Ship及其?reads

标签: jsonscalaplayframeworkplay-json

解决方案


最简单的方法是从密封特征扩展所有案例类。这样 play-json 可以自动生成读取:

sealed trait Resident

case class Men (age: Int, sex: Int) extends Resident
case class Leg (color: String) extends Resident
case class Cat (legs: Int, color: String, leg1: Leg, leg2: Leg, leg3: Leg, leg4: Leg) extends Resident
case class Bird (...) extends Resident

object Resident {
  private val cfg = JsonConfiguration(
      discriminator = "type",

      typeNaming = JsonNaming { fullName =>
        fullName
          .replaceFirst(".*[.]", "")
          .toLowerCase
      }
    )

  implicit val reads = Json.configured(cfg).reads[Resident]
}

case class Ship (name: String, sea: String, size: Int, residents: Seq[Resident])

object Ship {
  implicit val reads: Reads[Ship] = Json.reads[Ship]
}

是一个完整的例子。


推荐阅读