3

Given a String : {'Name':'Bond','Job':'Agent','LastEntry':'15/10/2015 13:00'}

I want to parse it into a Map[String,String], I already tried this answer but it doesn't work when the character : is inside the parsed value. Same thing with the ' character, it seems to break every JSON Mappers...

Thanks for any help.

Community
  • 1
  • 1
Will
  • 2,057
  • 1
  • 22
  • 34

2 Answers2

3

Let

val s0 = "{'Name':'Bond','Job':'Agent','LastEntry':'15/10/2015 13:00'}"
val s = s0.stripPrefix("{").stripSuffix("}")

Then

(for (e <- s.split(",") ; xs = e.split(":",2)) yield xs(0) -> xs(1)).toMap

Here we split each key-value by the first occurrence of ":". Further this is a strong assumption, in that the key does not contain any ":".

elm
  • 20,117
  • 14
  • 67
  • 113
2

You can use the familiar jackson-module-scala that can do this in much better scale.

For example:

val src = "{'Name':'Bond','Job':'Agent','LastEntry':'15/10/2015 13:00'}"
val mapper = new ObjectMapper() with ScalaObjectMapper
mapper.registerModule(DefaultScalaModule)
val myMap = mapper.readValue[Map[String,String]](src)
Avihoo Mamka
  • 4,656
  • 3
  • 31
  • 44