播放2.1 JSON到Scala对象

播放2.1 JSON到Scala对象,scala,playframework-2.0,playframework-2.1,Scala,Playframework 2.0,Playframework 2.1,我有一个Scala案例课程 case class Example(name: String, number: Int) 和一个伴星 object Example { implicit object ExampleFormat extends Format[Example] { def reads(json: JsValue) = { JsSuccess(Example( (json \ "name").as[String], (json \

我有一个Scala案例课程

case class Example(name: String, number: Int)
和一个伴星

object Example {
  implicit object ExampleFormat extends Format[Example] {
    def reads(json: JsValue) = {
      JsSuccess(Example(
       (json \ "name").as[String],
       (json \ "number").as[Int]))
     }

     def writes(...){}
   }
}
它将JSON转换为Scala对象

当JSON有效时(即
{“name”:“name”,“number”:0}
它工作正常。但是,当
number
在引号中
{“name”:“name”,“number”:“0”}
时,我得到一个错误:
验证.error.expected.jsnumber


在这种情况下(假设数字有效),有没有办法将
String
隐式转换为
Int

多亏了帮助程序,您可以使用Json组合符轻松处理这种情况。我用Play2.1引入的新语法重新编写了Json格式化程序

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

object Example {
  // Custom reader to handle the "String number" usecase
  implicit val reader = (
    (__ \ 'name).read[String] and
    ((__ \ 'number).read[Int] orElse (__ \ 'number).read[String].map(_.toInt))
  )(Example.apply _)

  // write has no specificity, so you can use Json Macro
  implicit val writer = Json.writes[Example] 
}

object Test extends Controller {
  def index = Action {
    val json1 = Json.obj("name" -> "Julien", "number" -> 1000).as[Example]
    val json2 = Json.obj("name" -> "Julien", "number" -> "1000").as[Example]
    Ok(json1.number + " = " + json2.number) // 1000 = 1000
  }
}

谢谢!它可以做到。但是有没有更通用的解决方案。例如,如果我有像number1,number2这样的字段…?当然有更好的方法来做到这一点,但是看看这个解决方案