Play JSON读取:可以以多种类型显示的读取值

问题描述 投票:0回答:1

我有用于ship的JSON:

{
  "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中看到的那样,我有不同的居民:mencatbird,... 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是数组,其元素可以是不同的类型:MenCatBird。我想改为???读取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

arrays json scala types playframework
1个回答
0
投票

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

sealed trait Resident

case class Men (age: Int, sex: Int) extends Resident
case class Leg (color: String) extends Resident
case class Cat (type: String, 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]
}
© www.soinside.com 2019 - 2024. All rights reserved.