Scala如何通过数组读取json路径

时间:2016-03-24 01:59:29

标签: json scala

我的主要目标是进行转换,即从“数据/消息”到“帖子/内容”。 我的代码出了什么问题?我甚至无法访问数组中“message”的值。

<code>
    import play.api.libs.json._
    import play.api.libs.json.Reads._
    import play.api.libs.functional.syntax._

    def mapping(): JsObject = {
      val sjson =
          """
            {
              "data": [
                {"message": "A", "created_time": "a" },
                {"message": "B", "created_time": "b" }
              ],
              "page": "test"
            }
          """.stripMargin

      val json = Json.parse(sjson)

      val jsonReads =
         (__ \ 'data \\ 'message ).read[String]

      json.validate(jsonReads).map {
        case( message ) =>
          Json.obj("content" -> message)
      }.get
    }
</code>

1 个答案:

答案 0 :(得分:0)

回复你对这篇文章的评论,这是我更新的答案:

val sjson =
  """
    {
      "data": [
        {"message": "A", "created_time": "a" },
        {"message": "B", "created_time": "b" }
      ],
      "page": "test"
    }
  """.stripMargin

// Read the whole object
val json: JsObject = Json.parse(sjson).as[JsObject]

// Read the "data array"
val data: Seq[JsObject] = (json \ "data").as[Seq[JsObject]]

// Get final result my changing "data" to "posts",
// and all instances of "message" to "content" and "created_time" to "created"
val result =
  Json.obj(
    "posts" -> (data map (d => JsObject(d.value map {
      case ("message", m) =>
        "content" -> m
      case ("created_time", t) =>
        "created" -> t
    })))
  )