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
Over 2 million developers have joined DZone.
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
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives

Trending

  • Genkit Middleware: Intercept, Extend, and Harden your Gen AI Pipelines
  • Hallucination Has Real Consequences — Lessons From Building AI Systems
  • Ten Years of Beam: From Google's Dataflow Paper to 4 Trillion Events at LinkedIn
  • Context-Aware Authorization for AI Agents
  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 user avatar
Dheeraj Gupta
·
Updated Jul. 19, 21 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
14.2K Views

Join the DZone community and get the full member experience.

Join For Free

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
  • Stop Poisoning Your Models: How I Built a CV Dataset Quality Toolkit I Can Reuse Forever
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • 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