Frage

I try to migrate my web application from Play 2.0.4 to Play 2.1-RC2.

I have JSON data with a list of unknown keys (key1, key2) like this:

{description: "Blah",
 tags: [
   key1: ["value1", "value2"],
   key2: ["value3"]
 ]
}

I want to store the data from the JSON in a List of Metatags. In Play 2.0.4 I have used something like this to read the tags-list:

def readMetatags(meta: JsObject): List[Metatag] =
  meta.keys.toList.map(x => Metatag(x, (meta \ x).as[List[String]])

Now I want to use the new Play 2.1-JSON-API (Prototype):

import play.api.libs.json._
import play.api.libs.functional.syntax._

object Metatags {  
  implicit val metatagsRead: Read[Metatags] = (
    (JsPath \ "description").read[String] and
    (JsPath \ "tags").read[List[Metatag]]
  )(Metatags.apply _, unlift(Metatags.unapply _))

  implicit val metatagRead: Read[Metatag] = (
    JsPath().key. ?? read[String] and              // ?!? read key
    JsPath().values. ?? read[List[String]]         // ?!? read value list
  )(Metatag.apply _, unlift(Metatag.unapply _))

}

case class Metatags(description: String, tags: List[Metatag])
case class Metatag(key: String, data: List[String])

How can I read the keys from the JSON?

War es hilfreich?

Lösung

This is a solution with a custom reader for the MetaTag class. The read just convert the JsValue to a JsObject, which have the useful fieldSet method.

For MetaTags, the macro inception works perfectly

object Application extends Controller {

  case class MetaTags(description: String, tags: List[MetaTag])
  case class MetaTag(key: String, data: List[String])

  implicit val readMetaTag = Reads(js => 
    JsSuccess(js.as[JsObject].fieldSet.map(tag => 
      MetaTag(tag._1, tag._2.as[List[String]])).toList))

  implicit val readMetaTags = Json.reads[MetaTags]

  def index = Action {
    val json = Json.obj(
      "description" -> "Hello world",
      "tags" -> Map(
        "key1" -> Seq("key1a", "key1b"),
        "key2" -> Seq("key2a"),
        "key3" -> Seq("Key3a", "key3b", "key3c")))

    val meta = json.as[MetaTags]
    Ok(meta.tags.map(_.data.mkString(",")).mkString("/"))
    // key1a,key1b/key2a/Key3a,key3b,key3c
  }

}
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top