繁体   English   中英

什么是 Scala 3 相当于这个 Scala 2 使用枚举和 play-json 的代码?

[英]What is Scala 3 equivalent to this Scala 2 code that uses Enumeration and play-json?

我有一些在 Scala 2.{10,11,12,13} 中工作的代码,我现在正在尝试将其转换为 Scala 3. Scala 3 的枚举方式不同于 Scala 2. 我正在尝试找出如何转换以下代码与play-json交互,以便它可以与 Scala 一起使用 3. 任何提示或指针指向已经跨过此桥的项目的代码?

// Scala 2.x style code in EnumUtils.scala 
import play.api.libs.json._
import scala.language.implicitConversions

// see: http://perevillega.com/enums-to-json-in-scala
object EnumUtils {
  def enumReads[E <: Enumeration](enum: E): Reads[E#Value] =
    new Reads[E#Value] {
      def reads(json: JsValue): JsResult[E#Value] = json match {
        case JsString(s) => {
          try {
            JsSuccess(enum.withName(s))
          } catch {
            case _: NoSuchElementException =>
              JsError(s"Enumeration expected of type: '${enum.getClass}', but it does not appear to contain the value: '$s'")
          }
        }
        case _ => JsError("String value expected")
      }
    }
  implicit def enumWrites[E <: Enumeration]: Writes[E#Value] = new Writes[E#Value] {
    def writes(v: E#Value): JsValue = JsString(v.toString)
  }
  implicit def enumFormat[E <: Enumeration](enum: E): Format[E#Value] = {
    Format(EnumUtils.enumReads(enum), EnumUtils.enumWrites)
  }
}
// ----------------------------------------------------------------------------------
// Scala 2.x style code in Xyz.scala
import play.api.libs.json.{Reads, Writes}

object Xyz extends Enumeration {
  type Xyz = Value
  val name, link, unknown = Value
  implicit val enumReads: Reads[Xyz] = EnumUtils.enumReads(Xyz)
  implicit def enumWrites: Writes[Xyz] = EnumUtils.enumWrites
}

作为一个选项,您可以切换到jsoniter-scala

它开箱即用地支持 Scala 2 和 Scala 3 的枚举。

它还可以方便地派生出安全高效的 JSON 编解码器。

只需要将所需的库添加到您的依赖项中:

libraryDependencies ++= Seq(
  // Use the %%% operator instead of %% for Scala.js and Scala Native 
  "com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-core"   % "2.13.5",
  // Use the "provided" scope instead when the "compile-internal" scope is not supported  
  "com.github.plokhotnyuk.jsoniter-scala" %% "jsoniter-scala-macros" % "2.13.5" % "compile-internal"
)

然后导出一个编解码器并使用它:

import com.github.plokhotnyuk.jsoniter_scala.core._
import com.github.plokhotnyuk.jsoniter_scala.macros._

implicit val codec: JsonValueCodec[Xyz.Xyz] = JsonCodecMaker.make

println(readFromString[Xyz.Xyz]("\"name\""))

顺便说一句,您可以在 Scastie 上运行完整代码: https://scastie.scala-lang.org/Evj718q6TcCZow9lRhKaPw

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM