PlayFramework:如何转换JSON数组的每个元素

时间:2015-05-08 17:57:19

标签: scala playframework

给出以下JSON ......

{
  "values" : [
     "one",
     "two",
     "three"
  ]
}

...如何在Scala / Play中将其转换为这样?

{
  "values" : [
     { "elem": "one" },
     { "elem": "two" },
     { "elem": "three" }
  ]
}

2 个答案:

答案 0 :(得分:6)

使用Play's JSON Transformers

很容易
val json = Json.parse(
  """{
    |  "somethingOther": 5,
    |  "values" : [
    |     "one",
    |     "two",
    |     "three"
    |  ]
    |}
  """.stripMargin
)

// transform the array of strings to an array of objects
val valuesTransformer = __.read[JsArray].map {
  case JsArray(values) =>
    JsArray(values.map { e => Json.obj("elem" -> e) })
}

// update the "values" field in the original json
val jsonTransformer = (__ \ 'values).json.update(valuesTransformer)

// carry out the transformation
val transformedJson = json.transform(jsonTransformer)

答案 1 :(得分:2)

您可以使用Play的JSON API:

import play.api.libs.json._

val json = Json parse """
    {
      "values" : [
         "one",
         "two",
         "three"
      ]
    }
  """

val newArray = json \ "values" match {
  case JsArray(values) => values.map { v => JsObject(Seq("elem" -> v)) }
}

// or Json.stringify if you don't need readability
val str = Json.prettyPrint(JsObject(Seq("values" -> JsArray(newArray))))

输出:

{
  "values" : [ {
    "elem" : "one"
  }, {
    "elem" : "two"
  }, {
    "elem" : "three"
  } ]
}