Home » JavaScript » Working with JSON in Scala.js

About Zakaria Amine

Zakaria Amine
Zakaria is a freelance software engineer who enjoys working with Java web frameworks, and microservice architectures. During his free time, Zakaria works on hobby projects, and blogs about his favorite topics like GWT and Spring.

Working with JSON in Scala.js

Introduction

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: String, brand: String, model: String) {}

using scalajs-dom requires a slight modification to the object as only js.Object is allowed

class Car extends js.Object {
  var id: String = _
  var brand: String = _
  var model: String = _
}

Serializing

  • uPickle:

Using uPickle, it is enough to create an object that configures the types to be read/written :

import upickle.default.{ReadWriter => RW, macroRW}

object Car{
  implicit def rw: RW[Car] = macroRW
}

and then:

val mercedes = new Car("1", "Mercedes", "2015")
    
    val mercedesJSON = write[Car](mercedes)

     println(mercedesJSON)

     //result: {"id":"1","brand":"Mercedes","model":"2015"}
  • Circe:

Circe requires the configuration of encoders/decoders:

import io.circe.{Decoder, Encoder}
import io.circe.generic.semiauto._

object Expense {
  implicit val carDecoder: Decoder[Car] = deriveDecoder
  implicit val carEncoder: Encoder[Car] = deriveEncoder
}

and then:

import io.circe.syntax._

    val mercedes = new Car("1", "Mercedes", "2015")

    val mercedesJSON = mercedes.asJson

    println(mercedes.asJson)
     
     //result is indented by default �� for making the output oneline : .asJson.noSpaces
     /*  {
      "id": "1",
      "brand": "Mercedes",
      "model": "2015"
      }
      */
  • 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 :

val mercedes = new Car()
    mercedes.id = "10"
    mercedes.model = "1980"
    mercedes.brand = "Mercedes"
    println(JSON.stringify(mercedes))

    //result: {"id":"10","brand":"Mercedes","model":"1980"}

Deserializing

  • uPickle:
val mercedesJSON = """{"id":"10","brand":"Mercedes","model":"1980"}"""
    val mercedes = read[Car](mercedesJSON)
    println(mercedes.id)
    // 10
    println(mercedes.model)
    //  1980
    println(mercedes.brand)
    // Mercedes
  • Circe:
val mercedesJSON = """{"id":"10","brand":"Mercedes","model":"1980"}"""
    val mercedes = decode[Car](mercedesJSON).toTry.get
    println(mercedes.id)
    // 10
    println(mercedes.model)
    //  1980
    println(mercedes.brand)
    // Mercedes
  • scalajs-dom:
val mercedesJSON = """{"id":"10","brand":"Mercedes","model":"1980"}"""
    val mercedes = JSON.parse(mercedesJSON).asInstanceOf[Car]
    println(mercedes.id)
    // 10
    println(mercedes.model)
    //  1980
    println(mercedes.brand)
    // Mercedes

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.

Published on Web Code Geeks with permission by Zakaria Amine, partner at our WCG program. See the original article here: Working with JSON in Scala.js

Opinions expressed by Web Code Geeks contributors are their own.

(0 rating, 0 votes)
You need to be a registered member to rate this.
Start the discussion Views Tweet it!
Do you want to know how to develop your skillset to become a Web Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. Building web apps with Node.js
2. HTML5 Programming Cookbook
3. CSS Programming Cookbook
4. AngularJS Programming Cookbook
5. jQuery Programming Cookbook
6. Bootstrap Programming Cookbook
and many more ....
I agree to the Terms and Privacy Policy

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of