2
votes

I'm working with Play Framework 2.3.4 and I'm trying to write a simple implicit Reads function that should be able to take an arbitrary number of keys in the json object and produce a Seq of domain objects.

For example, the JSON might look like this:

{ "key1" : "value1", "key2" : "value2", ... "keyN" : "valueN" }

I have a domain object like so:

case class DomainObject(key: String, value: String)

and I'd like to write something using Play JSON to produce a Seq[DomainObject].

So in this case, if we had only two keys, I'd have a Seq of two DomainObjects, the first with key = "key1" and value = "value1" and the second with the key "key2" and value = "value2"

Thanks for the help.

1

1 Answers

3
votes

Maybe there is a way to create nice writer to do this, but the simple solution would be:

scala> val myJson = Json.parse("""{ "key1" : "value1", "key2" : "value2", "keyN" : "valueN" }""")
myJson: play.api.libs.json.JsValue = {"key1":"value1","key2":"value2","keyN":"valueN"}

scala> myJson.as[Map[String,String]] map {case (key, value) => DomainObject(key, value)}
res8: scala.collection.immutable.Iterable[DomainObject] = List(DomainObject(key1,value1), DomainObject(key2,value2), DomainObject(keyN,valueN))

Instead of building some complex writer all you need to do is convert it to a Map[String, String] (which for that you have writer out of the box), and then map each key-value pairs to the DomainObject.