【问题标题】:Play 2.1 JSON to Scala object播放 2.1 JSON转Scala对象
【发布时间】:2013-01-11 03:49:30
【问题描述】:

我有一个 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"} 我得到一个错误:validate.error.expected.jsnumber

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

【问题讨论】:

    标签: scala playframework-2.0 playframework-2.1


    【解决方案1】:

    借助 orElse 帮助器,您可以使用 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... 之类的字段?
    • 当然有更好的方法来做到这一点,但看看这个解决方案gist.github.com/02dca6d1b77f0be6bf72
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-22
    • 1970-01-01
    • 2012-09-17
    • 1970-01-01
    • 2021-03-07
    • 2013-07-11
    • 1970-01-01
    相关资源
    最近更新 更多