Open In App

How to Create a JSON Object in Scala?

Last Updated : 28 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

JSON(JavaScript Object Notation) plays an important role in web development and data transmission. In web applications, we frequently use JSON, a lightweight data transmission standard. Working with JSON data is made easy using Scala, a sophisticated programming language for the Java Virtual Machine (JVM). This article focuses on discussing how to create a JSON object in Scala.

Here are a few important applications of JSON in Scala:

  1. Data transmission
  2. Serialization and Deserialization
  3. Data Processing
  4. Data Analysis
  5. Testing
  6. Frontend – Backend configurations

Example 1:

The below Scala program implements how to create a JSON object.

Scala
object Main{
   def main(args: Array[String]) {
    val jObject = Map(
      "Name" -> "Jimin",
      "Age" -> 26,
      "City" -> "Seoul"
    );
    val jString = mapToJsonString(jObject);
    println(jString);
  };
  def mapToJsonString(map: Map[String, Any]): String = {
    val ele = map.map {
      case (key, value) => "\"" + key + "\":" + valueToJsonString(value);
    };
    "{" + ele.mkString(",") + "}";
  };
  def valueToJsonString(value: Any): String = value match {
    case s: String => "\"" + s + "\"";
    case _ => value.toString;
   };
};

Output
{"Name":"Jimin","Age":26,"City":"Seoul"}

Explanation:

  1. In the above code, We have Created a JSON – like map i.e., val jObject = Map().
  2. Next we have Converted into to JSON – like string i.e., val jString = mapToJsonString(jObject).
  3. Above step calls for a function mapToJsonString.
  4. This function takes a Map[String, Any] and converts it into a JSON-like string.
  5. It iterates over map and constructs a string in format of key-value pair using the valueToJsonString function. valueToJsonString Function converts a value to a JSON string using toString Method.
  6. Later we have printed the jString.

Example 2:

In this example, Let us use built-in scala.collection.mutable.Map data structure. This data structure helps us to create a key – value pairs like a JSON object.

Scala
import scala.collection.mutable.Map;
object Main {
   def main(args: Array[String]) {
      val jObject = Map(
  "Name" -> "Jimin",
  "Age" -> 26,
  "Contact" -> "9xxx5xxx35"
).withDefaultValue("");
println(jObject("Name"));   
println(jObject("Age"));  
println(jObject("Contact"));  
   }
}

Output
Jimin
26
9xxx5xxx35

Explanation:

  1. In the above Example we have imported a data structure scala.collection.mutable.Map.
  2. We have Created a JSON – like map i.e., val jObject = Map(). withDefaultValue(“”) is used to provide default values for keys which are not explicitly defined.
  3. We can access the values of a JSON object using keys.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads