DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps
  • JSON Handling With GSON in Java With OOP Essence
  • Constrained Decoding Models Explained: Encoders, Decoders and When to Use Them
  • Building a Reddit Scraper in Go: JSON Listings, Pagination, Rate Limits, and Where It Breaks

Trending

  • A Non-Expiring AKS Deployment Token Could Read Secrets Across Three Namespaces
  • How to Evaluate Coding Agents With Harbor Framework, Python, Docker
  • When 12 Hours of Offline Changes Collide: Designing Conflict-Safe Mobile Sync
  • Decoupling a Data Pipeline From the Tables It Was Never Supposed to Depend On

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Languages
  4. Let's Unblock: Read Json Using GSON in Scala

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.

By 
Dheeraj Gupta
·
Updated Jul. 19, 21 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
14.5K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

What 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:

XML
 
<!-- 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:

Scala
 
// 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.

Scala
 
  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).

Scala
 
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.

Gson Scala (programming language) JSON

Opinions expressed by DZone contributors are their own.

Related

  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps
  • JSON Handling With GSON in Java With OOP Essence
  • Constrained Decoding Models Explained: Encoders, Decoders and When to Use Them
  • Building a Reddit Scraper in Go: JSON Listings, Pagination, Rate Limits, and Where It Breaks

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook