使用 Scala CLI,您可以在單一行中要求整個工具組
//> using toolkit latest
或者,您也可以只要求特定版本的 UPickle
//> using dep com.lihaoyi::upickle:3.1.0
在您的 build.sbt 檔案中,您可以新增對工具組的相依性
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"
讀取和寫入原始 JSON
要讀寫 JSON 檔案,您可以使用 uJson 和 OS-Lib,如下所示
// read a JSON file
val json = ujson.read(os.read(os.pwd / "raw.json"))
// modify the JSON content
json("updated") = "now"
//write to a new file
os.write(os.pwd / "raw-updated.json", ujson.write(json))
使用 JSON 讀寫 Scala 物件
要讀寫 Scala 物件到 JSON 檔案,您可以使用 uPickle 和 OS-Lib,如下所示
import upickle.default._
case class PetOwner(name: String, pets: List[String])
implicit val ownerRw: ReadWriter[PetOwner] = macroRW
// read a PetOwner from a JSON file
val petOwner: PetOwner = read[PetOwner](os.read(os.pwd / "pet-owner.json"))
// create a new PetOwner
val petOwnerUpdated = petOwner.copy(pets = "Toolkitty" :: petOwner.pets)
// write to a new file
os.write(os.pwd / "pet-owner-updated.json", write(petOwnerUpdated))
import upickle.default.*
case class PetOwner(name: String, pets: List[String]) derives ReadWriter
// read a PetOwner from a JSON file
val petOwner: PetOwner = read[PetOwner](os.read(os.pwd / "pet-owner.json"))
// create a new PetOwner
val petOwnerUpdated = petOwner.copy(pets = "Toolkitty" :: petOwner.pets)
// write to a new file
os.write(os.pwd / "pet-owner-updated.json", write(petOwnerUpdated))
要將 Scala case 類別 (或列舉) 序列化和反序列化為 JSON,我們需要 ReadWriter
的實例。要了解 uPickle 如何為您產生它,您可以閱讀 如何將 JSON 反序列化為物件? 或 如何將物件序列化為 JSON? 教學課程。