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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Jackson vs Gson: Edge Cases in JSON Parsing for Java Apps
  • JSON Handling With GSON in Java With OOP Essence
  • Streamlining Event Data in Event-Driven Ansible
  • Thermometer Continuation in Scala

Trending

  • How to Configure and Customize the Go SDK for Azure Cosmos DB
  • A Modern Stack for Building Scalable Systems
  • Beyond Linguistics: Real-Time Domain Event Mapping with WebSocket and Spring Boot
  • Streamlining Event Data in Event-Driven Ansible
  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
DZone Core CORE ·
Updated Jul. 19, 21 · Tutorial
Likes (6)
Comment
Save
Tweet
Share
13.7K 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
  • Streamlining Event Data in Event-Driven Ansible
  • Thermometer Continuation in Scala

Partner Resources

×

Comments
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!