Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I deserialize a JSON array using the Play API

I have a string that is a Json array of two objects.

> val ss = """[ {"key1" :"value1"}, {"key2":"value2"}]"""

I want to use the Play Json libraries to deserialize it and create a map from the key values to the objects.

def deserializeJsonArray(ss:String):Map[String, JsValue] = ???
// Returns Map("value1" -> {"key1" :"value1"}, "value2" -> {"key2" :"value2"})

How do I write the deserializeJsonArray function? This seems like it should be easy, but I can't figure it out from either the Play documentation or the REPL.

like image 285
W.P. McNeill Avatar asked Mar 20 '26 00:03

W.P. McNeill


1 Answers

I'm a bit rusty, so please forgive the mess. Perhaps another overflower can come in here and clean it up for me.

This solution assumes that the JSON is an array of objects, and each of the objects contains exactly one key-value pair. I would highly recommend spicing it up with some error handling and/or pattern matching to validate the parsed JSON string.

def deserializeJsonArray(ss: String): Map[String, JsValue] = {

  val jsObjectSeq: Seq[JsObject] = Json.parse(ss).as[Seq[JsObject]]

  val jsValueSeq: Seq[JsValue] = Json.parse(ss).as[Seq[JsValue]]

  val keys: Seq[String] = jsObjectSeq.map(json => json.keys.head)

  (keys zip jsValueSeq).toMap
}
like image 131
David Kaczynski Avatar answered Mar 22 '26 16:03

David Kaczynski



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!