How to Create a JSON Object in Scala?
Last Updated :
28 Mar, 2024
Improve
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:
- Data transmission
- Serialization and Deserialization
- Data Processing
- Data Analysis
- Testing
- Frontend - Backend configurations
Example 1:
The below Scala program implements how to create a JSON object.
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:
- In the above code, We have Created a JSON - like map i.e., val jObject = Map().
- Next we have Converted into to JSON - like string i.e., val jString = mapToJsonString(jObject).
- Above step calls for a function mapToJsonString.
- This function takes a Map[String, Any] and converts it into a JSON-like string.
- 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.
- 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.
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:
- In the above Example we have imported a data structure scala.collection.mutable.Map.
- 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.
- We can access the values of a JSON object using keys.