简体   繁体   English

如何解析scala中的mutableList作为播放框架2.0上的JSON?

[英]How do I parse a mutableList in scala as JSON on play framework 2.0?

I am working on Play Framework 2.0 and it uses Jerkson to parse JSON strings. 我正在使用Play Framework 2.0,它使用Jerkson来解析JSON字符串。 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? 有谁知道我怎么能这么做?

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 : 由于在当前主干中用traversableReads替换了seqReads ,你的第二行将在Play 2.0的未来版本中运行:

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. 所以,如果你愿意从源头构建Play ,或者等待,你就没事了。 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 . 否则你应该能够在你自己的代码中的某个地方删除方法,以在范围内获得适当的Reads实例,或者甚至更好 - 只使用Alexey Romanov的解决方案,或者最好 - 不要使用MutableList

Eg new MutableList[String]() ++= Json.parse( jsonStr ).as[ List[String] ] (assuming @DanSimon is correct about which MutableList you mean). 例如, new MutableList[String]() ++= Json.parse( jsonStr ).as[ List[String] ] (假设@DanSimon关于你的意思是哪个MutableList是正确的)。 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 . 但是Scala中最常用的可列表类似集合是一个Buffer ,它可以作为Buffer(Json.parse( jsonStr ).as[ List[String] ]Json.parse( jsonStr ).as[ List[String] ].toBuffer

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM