Scala Convert Map to JSON

1. Introduction

Converting a map to a JSON object is a common requirement in Scala, particularly in web development and APIs, where data interchange often occurs in JSON format. Scala provides various libraries for JSON handling, and in this post, we will use the Play JSON library to demonstrate how to convert a map to a JSON object.

2. Program Steps

1. Add the Play JSON library dependency to the Scala project.

2. Create a Scala map with some data.

3. Convert the map to a JSON object using the Play JSON library.

4. Print the JSON object to verify the conversion.

5. Execute the program to observe the output.

3. Code Program

import play.api.libs.json.Json

object MapToJsonDemo extends App {
  val dataMap: Map[String, Any] = Map(
    "name" -> "John Doe",
    "age" -> 30,
    "isStudent" -> false
  )

  // Converting map to JSON
  val json = Json.toJson(dataMap)
  println("Map converted to JSON:")
  println(json)
}

Output:

Map converted to JSON:
{"name":"John Doe","age":30,"isStudent":false}

Explanation:

1. The Play JSON library's Json.toJson method is used to convert the Scala map dataMap into a JSON object.

2. The map's keys and values are automatically transformed into JSON keys and values.

3. The output shows the JSON representation of the map, which can be used for data interchange in web applications or APIs.


Comments