The Scala Toolkit

What else can uPickle do?

Language

Using Scala CLI, you can require the entire toolkit in a single line:

//> using toolkit latest

Alternatively, you can require just a specific version of UPickle:

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

In your build.sbt file, you can add the dependency on the Toolkit:

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

Alternatively, you can require just a specific version of UPickle:

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

In your build.sc file, you can add the dependency to the upickle library:

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

Alternatively, you can require just a specific version of UPickle:

ivy"com.lihaoyi::upickle:3.1.0"

Construct a new JSON structure with uJson

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/",
)

Learn more about constructing JSON in the uJson documentation.

Defining custom JSON serialization

You can customize the ReadWriter of your data type by mapping the ujson.Value, like this:

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"]

Learn more about custom JSON serialization in the uPickle documentation.

Contributors to this page: