3

I am working on Play Framework 2.0 and it uses Jerkson to parse JSON strings. I was using it successfully to parse Immutable Lists of strings like so:

Json.parse( jsonStr ).as[ List[String] ]

But this code doesn't work for me when I try

Json.parse( jsonStr ).as[ MutableList[String] ]

Does anyone know how I can do this easily?

Samuel
  • 1,667
  • 12
  • 18
wynnch
  • 545
  • 2
  • 5
  • 17
  • @missingfaktor I think he's referring to [scala.collection.mutable.MutableList](http://www.scala-lang.org/api/current/scala/collection/mutable/MutableList.html) – Dan Simon Jun 18 '12 at 18:27
  • @DanSimon, thanks. Three years of Scala, and this is the first time I am seeing that class. – missingfaktor Jun 18 '12 at 18:53

2 Answers2

3

Your second line will work as it is in a future version of Play 2.0, thanks to the replacement of seqReads by traversableReads in the current trunk:

implicit def traversableReads[F[_], A](implicit bf: generic.CanBuildFrom[F[_], A, F[A]], ra: Reads[A]) = new Reads[F[A]] {
  def reads(json: JsValue) = json match {
    case JsArray(ts) => {
      val builder = bf()
      for (a <- ts.map(fromJson[A](_))) {
        builder += a
      }
      builder.result()
    }
    case _ => throw new RuntimeException("Collection expected")
  }
}

So if you're willing to build Play from source, or to wait, you're fine. Otherwise you should be able to drop the method above somewhere in your own code to get an appropriate Reads instance in scope, or—even better—just use Alexey Romanov's solution, or—best of all—don't use MutableList.

Travis Brown
  • 138,631
  • 12
  • 375
  • 680
  • Sorry, but where exactly should I put this method in my code? – wynnch Jun 18 '12 at 21:26
  • It's an implicit method that creates an instance of the `Reads` [type class](http://stackoverflow.com/questions/5408861/what-are-type-classes-in-scala-useful-for) for collection types as needed, so you should be able to put it anywhere in scope (you may need to add an import for—or qualify the call to—`Json.fromJson`). – Travis Brown Jun 18 '12 at 22:46
2

E.g. new MutableList[String]() ++= Json.parse( jsonStr ).as[ List[String] ] (assuming @DanSimon is correct about which MutableList you mean). But the most used mutable list-like collection in Scala is a Buffer which could be obtained as Buffer(Json.parse( jsonStr ).as[ List[String] ] or Json.parse( jsonStr ).as[ List[String] ].toBuffer.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487