【问题标题】:Extract Json attribute value from JsArray ( play )从 JsArray 中提取 Json 属性值 ( play )
【发布时间】:2015-11-16 21:50:10
【问题描述】:

以下是我的 scala 代码中的 sn-p。我正在使用播放 2.4。以下是我的“消息”验证的输出。

import play.api.libs.json._

              .map{ _ match {
                  case (Some( message :JsArray  ), x) => {
                       println(      message  )
                       println((message \\ "collectorId").map(_.as[Int]))
                   }
               }

输出:

["{\"id\":1,\"createdAt\":\"2015-11-11T16:18:58.789\",\"collectorId\":4}", "{\"id\":5,\"createdAt\":\"2015-11-11T22:35:52.300\",\"collectorId\":5}", "{\"id\":2,\"createdAt\":\"2015-11-11T16:21:05.377\",\"collectorId\":4}", "{\"id\":3,\"createdAt\":\"2015-11-11T22:35:20.408\",\"collectorId\":2}", "{\"id\":4,\"createdAt\":\"2015-11-11T22:35:38.602\",\"collectorId\":4}"]

ListBuffer()

如何提取

“收集器ID”

值作为 Seq[Int]。当我执行代码时,我得到它作为 ListBuffer()。

我发现 JsObject 应该在那里代替 JsArray。

感谢大家的支持。以下是我解决问题的方法。

case (Some( message :JsArray ), response ) => {
       (message \\ "collectorId").map{_ match { case JsNumber(s) =>  s.intValue() }
       }
}

【问题讨论】:

  • message \\ "collectorId" 是否会返回给您Seq[JsValue]
  • 我没有得到这个问题。你想要List 而不是ListBuffer。如果是这样,请使用.toList
  • 如何将“collectorId”值提取为 Seq[Int]

标签: json scala playframework play-json


【解决方案1】:

使用

(message \\ "collectorId" map(_.as[Int]) toSeq
//> res0: Seq[Int] = List(4, 5, 4, 2, 4)

其中messageJArray

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-27
    • 2017-02-06
    • 1970-01-01
    相关资源
    最近更新 更多