【问题标题】:Get a Json format for a Seq of a generic type获取泛型 Seq 的 Json 格式
【发布时间】:2017-03-10 14:12:58
【问题描述】:

我有一个泛型类型的抽象类,它从其子类中获取该泛型类型的 Json 格式。但抽象类也需要该类型序列的 Json 格式。在 Scala 中是否有任何方法可以仅根据这些事物的格式来获取一系列事物的 Json 格式?

我正在使用 Play Json 框架。

这是一个不完全符合我的情况的示例,但很好地表明了我想要实现的目标:

  package scalatest

  import scala.concurrent.Future
  import scala.concurrent.ExecutionContext.Implicits.global
  import scala.concurrent.Await
  import scala.concurrent.duration.Duration
  import java.util.UUID
  import scala.util.control.NonFatal
  import play.api.libs.json.Format
  import play.api.libs.json.Json

  object Banana {

     def main(args: Array[String]): Unit = {
        val f: Format[Seq[Banana]] = getSeqFormat(Json.format[Banana])
     }

     def getSeqFormat[T](format: Format[T]): Format[Seq[T]] = {
        ??? // TODO implement
     }
  }

  case class Banana(color: String)

【问题讨论】:

    标签: json scala generics play-json


    【解决方案1】:

    如果您只是想将香蕉序列化为 JSON 对象,那么您唯一需要做的就是定义 Banana implicit json 格式,其他的(例如 Seq 格式)是内置在游戏中:

    import play.api.libs.json.Json
    
    case class Banana(color: String)
    object Banana {
      implicit val jsonFormat = Json.writes[Banana]
    }
    
    object PlayJsonTest extends App {
      val bananas = Seq(Banana("yellow"), Banana("green"))
      println(Json.toJson(bananas)) // [{"color":"yellow"},{"color":"green"}]
    }
    

    这也适用于其他类型,因为Json#toJson 方法定义如下:

    // Give me an implicit `Writes[T]` and I know how to serialize it
    def toJson[T](o: T)(implicit tjs: Writes[T]): JsValue = tjs.writes(o)
    

    默认值是隐式使用的,其中包括大多数集合的格式。你可以找到他们here

    希望对你有帮助。

    【讨论】:

    • 感谢您的回答,但它不适用于我的问题。如果您有 Bananas 的格式,Play 会隐含地为您提供 Bananas 的 Seq 格式。但是,这不适用于泛型类型的格式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-22
    相关资源
    最近更新 更多