anako
anako

Reputation: 125

play scala reads for Map[Int,List[String]] with exeptions

I'm using Scala and Play framework. So I have a structure that is Map[Int, List[String]] and I need to define a formatter for that. I also need not only to parse keys as Ints, but get en error if one of the keys wasn't parsed succesfully. Here's what I've tried to code, but apperently it doesn't work.

def mapReads: Reads[Map[Int, List[String]] = new Reads[Map[Int, List[String]] {
def reads(myJs: JsValue): JsResult[Map[Int, List[String]] =
    (myJs.as[Map[String, List[String]].map{case (k, v) =>
        Integer.parseInt(k) -> v
    }).map(JsSuccess(_)).getOrElse(JsError("Key was not Integer"))
}

Would really appreciate any help!

Upvotes: 0

Views: 167

Answers (1)

pme
pme

Reputation: 14803

This should work for you:

import play.api.libs.json._

implicit val mapReads: Reads[Map[Int, List[String]]] = new Reads[Map[Int, List[String]]] {
    def reads(jv: JsValue): JsResult[Map[Int, List[String]]] =
        JsSuccess(jv.as[Map[String, List[String]]]
                    .map{
                        case (k, v:List[String]) => Integer.parseInt(k) -> v
                     })
}

Try it out:

val json = Json.parse("""{ "1": ["one", "two"] }""")

println(json.validate[Map[Int, List[String]]])

Upvotes: 1

Related Questions