Working with JSON is almost inevitable regardless of the environment. In this post, we will go through different ways of serializing/deserializing (or encoding/decoding as some may call it) objects from/to JSON in Scala.js. As of the date this post is written, there are three main tools that convert objects to/from JSON:
We will use the following object for all the examples for uPickle and Circe:
case class Car(id_disqus: String, brand: String, model: String) {}
using scalajs-dom requires a slight modification to the object as only js.Object is allowed
Serializing
uPickle:
Using uPickle, it is enough to create an object that configures the types to be read/written :
and then:
Circe:
Circe requires the configuration of encoders/decoders:
and then:
scalajs-dom:
using scalajs-dom requires the addition of scalacOptions += "-P:scalajs:sjsDefinedByDefault" to the build file, since @ScalaJSDefined is meant to be deprecated.
and then :
Deserializing
uPickle:
Circe:
scalajs-dom:
Wrap up
We have walked through different libraries that allow serializing/deserializing JSON in Scala.Js. All the methods work in pretty much the same way, so there is no preferred way. The choice is left to the developer.