PGS
PGS

Reputation: 1184

How to convert JSON String to Map in Scala

I am having JSON String passed from POST method of REST URL. I need to convert json string to map of type Map

JSON String looks like below

{"key_value": {"1":"1000","2":"2000"}}

How to convert into Map using scala.

Upvotes: 0

Views: 6873

Answers (1)

Alvaro Carrasco
Alvaro Carrasco

Reputation: 6172

You'll need a JSON parser library. Here it is with play-json:

import play.api.libs.json.Json
val jsonString = """{"key_value": {"1":"1000","2":"2000"}}"""
val aMap = (Json.parse(jsonString) \ "key_value").as[Map[String,String]]

Documentation for the path operations: https://www.playframework.com/documentation/2.5.x/ScalaJson#Simple-path-\

If you're using SBT, you can import it like this:

// https://mvnrepository.com/artifact/com.typesafe.play/play-json_2.11
libraryDependencies += "com.typesafe.play" % "play-json_2.11" % "2.5.5"

Upvotes: 1

Related Questions