加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala – 使用Argonaut在JSON数组上进行映射

发布时间:2020-12-16 09:54:11 所属栏目:安全 来源:网络整理
导读:我很难通过Argonaut文档,所以我想我只想问一个简单的例子. val input = """{"a":[{"b":4},{"b":5}]}"""val output = ??? // desired value: List(4,5) 我可以将光标放到数组中: Parse.parse(input).map((jObjectPL = jsonObjectPL("a") = jArrayPL)(_))// s
我很难通过Argonaut文档,所以我想我只想问一个简单的例子.

val input = """{"a":[{"b":4},{"b":5}]}"""

val output = ??? // desired value: List(4,5)

我可以将光标放到数组中:

Parse.parse(input).map((jObjectPL >=> jsonObjectPL("a") >=> jArrayPL)(_))
// scalaz./[String,Option[scalaz.IndexedStore[argonaut.Argonaut.JsonArray,//  argonaut.Argonaut.JsonArray,argonaut.Json]]] =
// /-(Some(IndexedStoreT((<function1>,List({"b":4},{"b":5})))))

但那又怎样?我是在正确的轨道上吗?我甚至应该使用游标吗?

编辑 – 我想这是一些进展.我为列表写了一个解码器:

Parse.parse("""[{"b": 4},{"b": 5}]""")
  .map(_.as(IListDecodeJson(DecodeJson(_.downField("b").as[Int]))))
// scalaz./[String,argonaut.DecodeResult[scalaz.IList[Int]]] =
// /-(DecodeResult(/-([4,5])))

编辑 – 慢慢开始把它放在一起……

Parse.parse(input).map(_.as[HCursor].flatMap(_.downField("a").as(
  IListDecodeJson(DecodeJson(_.downField("b").as[Int])))))
// scalaz./[String,5])))

编辑 – 所以我想我到目前为止最好的解决方案是:

Parse.parse(input).map(_.as(
  DecodeJson(_.downField("a").as(
    IListDecodeJson(DecodeJson(_.downField("b").as[Int])).map(_.toList)
  ))
))

但是感觉有点冗长.

解决方法

您可以在Argonaut中使用新的 Monocle支持(我在这里使用Argonaut master,因为6.1里程碑仍在Monocle 0.5上),这样做非常好:

import argonaut._,Argonaut._
import scalaz._,Scalaz._
import monocle._,Monocle._

val lens =
  Parse.parSEOptional ^<-? 
  jObjectPrism        ^|-?
  index("a")          ^<-?
  jArrayPrism         ^|->>
  each                ^<-?
  jObjectPrism        ^|-?
  index("b")          ^<-?
  jIntPrism

然后:

scala> lens.getAll("""{"a":[{"b":4},{"b":5}]}""")
res0: scalaz.IList[Int] = [4,5]

运算符起初看起来很可怕,但你已经习惯了它们,而且组合的部分很自然地阅读.当然,由于这是一个镜头,除了getAll之外,还可以使用各种操作.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读