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.
sarveshseri
14k30 silver badges50 bronze badges
asked Aug 23, 2016 at 15:25
1 Answer 1
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"
answered Aug 23, 2016 at 15:28
5 Comments
PGS
.Thanks for the answer.I need to remove "key_value" from
"""{"key_value": {"1":"1000","2":"2000"}}"""
input string. Only this part i need to put in map {"1":"1000","2":"2000"} .Alvaro Carrasco
@Gopi Updated with just the value, not the key
PGS
Is it not possible with using play-json . Can we use something link json4s or iterate and put in map
PGS
Getting below error when doing the above 'Error:(170, 59) bad symbolic reference. A signature in DefaultReads.class refers to term time in package java which is not available. It may be completely missing from the current classpath, or the version on the classpath might be incompatible with the version used when compiling DefaultReads.class. val aMap = (Json.parse(jsonString) \ "key_value").as[Map[Integer, Long]]'
Alvaro Carrasco
That version might only work with java 8. Try version: 2.4.8
lang-scala