John Zeng John Zeng - 7 months ago 91
Java Question

Java/Scala lib to parse dot-notation to Json string

I wanna parse some dot-notation map to a json string, for example I have:

input["top.second.third0"] = 0
input["top.second.third1"] = "hello"


And then I want to get the following json string from this map :

{"top":{
"second":{
"third0":0,
"third1":"hello"
}
}
}


I know how to generate it by using split, I am asking if there is a Java/Scala library that can do that for me?

Answer

For Play JSON, you can parse such expression to JsPath and then use it.

import play.api.libs.json._

val components = input.split("\\.")

components.headOption match {
  case Some(p) => components.tail.foldLeft(JsPath \ p) { _ \ _ }
  case _ => /* cannot parse */ ???
}