gpt4 book ai didi

json - Play/Scala JSON 解析中的 if 语句?

转载 作者:行者123 更新时间:2023-12-02 05:23:13 24 4
gpt4 key购买 nike

有没有办法在使用 Scala/Play 解析 json 时执行条件逻辑?

例如,我想做如下的事情:

implicit val playlistItemInfo: Reads[PlaylistItemInfo] = (
(if(( (JsPath \ "type1").readNullable[String]) != null){ (JsPath \ "type1" \ "id").read[String]} else {(JsPath \ "type2" \ "id").read[String]}) and
(JsPath \ "name").readNullable[String]
)(PlaylistItemInfo.apply _)

在我假设的 JSON 解析示例中,有两种可能的方法来解析 JSON。如果该项目属于“type1”,则 JSON 中将有一个“type1”值。如果 JSON 中不存在或其值为 null/空,那么我想改为读取 JSON 节点“type2”。

上面的示例不起作用,但它让您了解我正在尝试做什么。

这可能吗?

最佳答案

使用 JSON 组合器执行此操作的正确方法是使用 orElse 。组合器的每个部分必须是 Reads[YourType] ,所以 if/else 不太有效,因为你的 if子句不返回 Boolean ,它返回Reads[PlaylistItemInfo]检查null这将永远是 trueorElse让我们合并一个Reads寻找 type1字段,第二个字段查找 type2字段作为后备。

这可能不符合您的确切结构,但想法如下:

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

case class PlaylistItemInfo(id: Option[String], tpe: String)

object PlaylistItemInfo {
implicit val reads: Reads[PlaylistItemInfo] = (
(__ \ "id").readNullable[String] and
(__ \ "type1").read[String].orElse((__ \ "type2").read[String])
)(PlaylistItemInfo.apply _)
}

// Read type 1 over type 2
val js = Json.parse("""{"id": "test", "type1": "111", "type2": "2222"}""")

scala> js.validate[PlaylistItemInfo]
res1: play.api.libs.json.JsResult[PlaylistItemInfo] = JsSuccess(PlaylistItemInfo(Some(test),111),)

// Read type 2 when type 1 is unavailable
val js = Json.parse("""{"id": "test", "type2": "22222"}""")

scala> js.validate[PlaylistItemInfo]
res2: play.api.libs.json.JsResult[PlaylistItemInfo] = JsSuccess(PlaylistItemInfo(Some(test),22222),)

// Error from neither
val js = Json.parse("""{"id": "test", "type100": "fake"}""")

scala> js.validate[PlaylistItemInfo]
res3: play.api.libs.json.JsResult[PlaylistItemInfo] = JsError(List((/type2,List(ValidationError(error.path.missing,WrappedArray())))))

关于json - Play/Scala JSON 解析中的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30246369/

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