-1

I have a Json request body that represents four key-value pairs. I am attempting to deserialise the Json body (a JsValue object) into a Map of Strings, Map[String, String], but I get the following error:

"JsUndefined("VALUE1" is not an object)".

Json example:

{
    "key1":"VALUE1",
    "key2":"VALUE2",
    "key3":"VALUE3",
    "key4":"VALUE4"
}

Deserialization example:

val jsonResult = request.body //type of JsValue
(jsonResult \ "KEY1" \ "KEY2" \ "KEY3" \ "KEY4").asOpt[Map[String, String]]

It seems that attempting to extract the key-value pairs with the above line does not work, and that doing them indivudually does actually work E.g:

val keyPair1 = (jsonResult \ "KEY1")
val keyPair2 = (jsonResult \ "KEY2")

Question

Is there a way to deserialize each key-value pair in the provided JSON, represented as a JsValue, into a Map[String, String] all at once?

Any help is appreciated.

Chris
  • 785
  • 10
  • 24

1 Answers1

2

The issue you have is that every time you do \, you access the next key in the path. For example, when doing:

jsonResult \ "KEY1" \ "KEY2" \ "KEY3" \ "KEY4"

you are trying to access the path:

KEY1.KEY2.KEY3.KEY4

which, does not exist in the provided json.

The path KEY1, has JsString("VALUE1"), and does not have a descendant, therefore you get the error mentioned above.

Instead, you can simply do:

val jsonString = """{
                   |    "key1":"VALUE1",
                   |    "key2":"VALUE2",
                   |    "key3":"VALUE3",
                   |    "key4":"VALUE4"
                   |}""".stripMargin

val json = Json.parse(jsonString).asOpt[Map[String, String]]
println(json)

Code run at Scastie.

Tomer Shetah
  • 8,413
  • 7
  • 27
  • 35
  • I'm starting with a `JsValue` Object. Even when I `toString()` the JsValue, and then pass that String into your code Snippet, a match statement I have on the 'json' variable (the Option[Map[String, String]]) never matches the Some(_) case, only the None case. – Chris Apr 12 '21 at 21:05
  • @Chris did you see the code snippet I added? Can you please create one of your own that reproduces your issue? – Tomer Shetah Apr 12 '21 at 21:37