2

为了减少从我无法更改的内部 Web 服务到 Internet 客户端的网络流量,我想减少 JSON 响应。

因此,Web 服务“中继”仅提取 JSON 响应的特定子集。

由于正在发生的只是将 JSON 从一种格式转换为另一种格式,因此我更愿意在 Play Framework 2.1 中使用新的 JSON 转换器(请参阅:http ://www.playframework.com/documentation/2.1.1/ScalaJsonTransformers )

为了增加难度,响应是一个不同 JSON 对象的数组,每个对象只需要两个字段。

作为一个特定的虚拟示例,我正在尝试转换以下 JSON:

[
  {
    "keyA": "keep this value",
    "keyB": [ {"value": "keep this value", "anotherValue": "keep this value" } ],
    "keyC": "drop this value"
  },
  {
    "keyA": "keep this value",
    "keyB": [ {"value": "keep this value", "anotherValue": "keep this value" } ],
    "keyD": "drop this value",
    "keyE": "drop this value"
  },
  {
    "keyA": "keep this value",
    "keyB": [ {"value": "keep this value", "anotherValue": "keep this value" } ],
    "extraRandomKeys": "drop this value",
    "fieldsWhichMayNotAlwaysAppear: "drop this value"
  }
]

进入:

[
  {
    "keyA": "keep this value",
    "keyB": [ {"value": "keep this value", "anotherValue": "keep this value" } ]
  },
  {
    "keyA": "keep this value",
    "keyB": [ {"value": "keep this value", "anotherValue": "keep this value" } ]
  },
  {
    "keyA": "keep this value",
    "keyB": [ {"value": "keep this value", "anotherValue": "keep this value" } ]
  }
]

我使用的模板方法是:

def relayWsResponse = Action {
  request =>
    Async {
      WS.url("http://internalhost/service")
        .get()
        .map(
        response => {
          Ok(
            response.json.transform(
              ???
            ).get
          )
        }
      )
    }
}
4

1 回答 1

3

它有效,但可能不是最佳选择:

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

val transformer: Reads[JsArray] = of[JsArray].map{
  case JsArray(xs) => JsArray(xs.flatMap{
    case x: JsObject => Some(
      x.transform(
        (__ \ "keyA").json.pickBranch and (__ \ "keyB").json.pickBranch reduce
      ).get
    )
  })
}
于 2013-06-06T22:48:49.060 回答