Scala 工具組

uPickle 還有什麼功能?

語言

使用 Scala CLI,您可以在單一行中要求整個工具組

//> using toolkit latest

或者,您也可以只要求特定版本的 UPickle

//> using dep com.lihaoyi::upickle:3.1.0

在你的 build.sbt 檔案中,你可以新增對 Toolkit 的依賴關係

lazy val example = project.in(file("example"))
  .settings(
    scalaVersion := "3.2.2",
    libraryDependencies += "org.scala-lang" %% "toolkit" % "0.1.7"
  )

或者,您也可以只要求特定版本的 UPickle

libraryDependencies += "com.lihaoyi" %% "upickle" % "3.1.0"

在你的 build.sc 檔案中,你可以新增對 upickle 函式庫的依賴關係

object example extends ScalaModule {
  def scalaVersion = "3.2.2"
  def ivyDeps =
    Agg(
      ivy"org.scala-lang::toolkit:0.1.7"
    )
}

或者,您也可以只要求特定版本的 UPickle

ivy"com.lihaoyi::upickle:3.1.0"

使用 uJson 建立新的 JSON 結構

val obj: ujson.Value = ujson.Obj(
  "library" -> "upickle",
  "versions" -> ujson.Arr("1.6.0", "2.0.0", "3.1.0"),
  "documentation" -> "https://com-lihaoyi.github.io/upickle/",
)

uJson 文件 中進一步了解如何建構 JSON。

定義自訂 JSON 序列化

你可以透過對應 ujson.Value 來自訂你的資料類型的 ReadWriter,如下所示

import upickle.default._

case class Bar(i: Int, s: String)

object Bar {
  implicit val barReadWriter: ReadWriter[Bar] = readwriter[ujson.Value]
    .bimap[Bar](
      x => ujson.Arr(x.s, x.i),
      json => new Bar(json(1).num.toInt, json(0).str)
    )
}

val bar = Bar(5, "bar")
val json = upickle.default.write(bar)
println(json)
// prints: [5, "bar"]
import upickle.default.*

case class Bar(i: Int, s: String)

object Bar:
  given ReadWriter[Bar] = readwriter[ujson.Value]
    .bimap[Bar](
      x => ujson.Arr(x.s, x.i),
      json => new Bar(json(1).num.toInt, json(0).str)
    )

val bar = Bar(5, "bar")
val json = upickle.default.write(bar)
println(json)
// prints: [5, "bar"]

uPickle 文件 中進一步了解自訂 JSON 序列化。

此頁面的貢獻者