Let's Unblock: Read Json Using GSON in Scala
Gson is a common Google library to de-serialize and parses json. This article shows you how to utilize it in Scala.
Join the DZone community and get the full member experience.
Join For FreeWhat Is GSON?
Question number 1, what is GSON? As per Wikipedia, GSON is a Java library to serialize and deserialize Java objects to JSON. Now, another question: what is serialize and deserialize? The dictionary meaning of serializing is to transmit anything in a particular order. In the technical context, word serialization refers to converting the state of the object so that it can be traversed over the network. In other words, converting objects into a byte stream. For Deserialization, vice versa.
The Problem Statement
How do you implement serialization in scala? Why should you choose GSON? Let's answer these questions step by step. Here is the fundamental guide/cheatsheet of implementing GSON.
The Steps for Serialization in Scala Using GSON
Add the GSON dependency in your build file such as POM.xml/build.sbt by adding the following lines:
<!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
Or, for build.sbt:
// https://mvnrepository.com/artifact/com.google.code.gson/gson
libraryDependencies += "com.google.code.gson" % "gson" % "2.8.2"
Create a POJO/case class for the JSON file you wish to read.
case class Person(
name: String,
address: List[Address]
)
case class Address(
city: String,
state: String
)
Now, create a Scala class to parse the JSON and convert it into the scala object (the main magic class).
import com.google.gson.{Gson, JsonObject}
object JsonFormatter {
def main (args: Array[String]): Unit = {
val gson = new Gson
// parse the file and stringinfy the input
// val jsonString: String = Source.fromFile("/home/dheeraj/jsonFilePath.json").mkString
// or create a json string
val jsonString: String = """
{"name":"Dheeraj","address":[{"city":"Ghaziabad","state":"UP"},{"city":"Delhi","state":"Delhi"}]}
"""
//Serialising the Json String to the Person Object in Scala.
val person:Person = gson.fromJson(jsonString,classOf[Person])
println(person)
}
}
And, we are done with our parser. It's as simple as that.
Advantages of Using GSON
Now, the answer to the other question. Why GSON? The main advantage of the GSON lies in the implementation of its usage, just use toJson/fromJson to deserialize and serialize the object. Secondly, while performing deserialization POJO definition is not needed to read the object.
Hope you like this small article on GSON with scala. We will come back in time with more stuff like this. Until then, keep smiling, and keep coding.
Opinions expressed by DZone contributors are their own.
Comments