gpt4 book ai didi

scala - Play 2.1 JSON 到 Scala 对象

转载 作者:行者123 更新时间:2023-12-01 13:35:06 26 4
gpt4 key购买 nike

我有一个 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

有没有办法隐式转换 StringInt在这种情况下(假设号码有效)?

最佳答案

由于 orElse ,您可以使用 Json 组合器轻松处理这种情况。 helper 。我用 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
}
}

关于scala - Play 2.1 JSON 到 Scala 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14551326/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com