用play-json转换JsArray

时间:2015-08-21 14:42:59

标签: json scala playframework play-json

json转换器中的大多数示例都是关于JsObject的。我尝试转换JsArray但得到了这个错误

val json = Json.parse("""[{"toto":1},{"toto":10},{"tata":2}]"""]


val transformer = (__ \'toto).json.update(__.read[JsNumber].map{o => JsNumber(3)})

json.as[JsArray].map(_.transform(transformer))

错误

java.lang.RuntimeException: expected KeyPathNode
  at play.api.libs.json.JsPath$.step$1(JsPath.scala:147)
  at play.api.libs.json.JsPath$.play$api$libs$json$JsPath$$buildSubPath$1(JsPath.scala:156)
  at play.api.libs.json.JsPath$$anonfun$createObj$1.apply(JsPath.scala:161)
  at play.api.libs.json.JsPath$$anonfun$createObj$1.apply(JsPath.scala:159)
  at scala.collection.IndexedSeqOptimized$class.foldl(IndexedSeqOptimized.scala:57)
  at scala.collection.IndexedSeqOptimized$class.foldLeft(IndexedSeqOptimized.scala:66)
  at scala.collection.mutable.WrappedArray.foldLeft(WrappedArray.scala:35)
  at play.api.libs.json.JsPath$.createObj(JsPath.scala:159)
  at play.api.libs.json.PathReads$$anonfun$jsUpdate$1$$anonfun$apply$15.apply(JsConstraints.scala:86)
  at play.api.libs.json.PathReads$$anonfun$jsUpdate$1$$anonfun$apply$15.apply(JsConstraints.scala:86)
  at play.api.libs.json.JsResult$class.map(JsResult.scala:81)
  at play.api.libs.json.JsSuccess.map(JsResult.scala:9)
  at play.api.libs.json.PathReads$$anonfun$jsUpdate$1.apply(JsConstraints.scala:86)
  at play.api.libs.json.PathReads$$anonfun$jsUpdate$1.apply(JsConstraints.scala:82)
  at play.api.libs.json.Reads$$anon$8.reads(Reads.scala:101)
  at play.api.libs.json.JsValue$class.transform(JsValue.scala:78)
  at play.api.libs.json.JsObject.transform(JsValue.scala:166)
  at $anonfun$1.apply(<console>:21)
  at $anonfun$1.apply(<console>:21)
  at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
  at scala.collection.TraversableLike$$anonfun$map$1.apply(TraversableLike.scala:245)
  at scala.collection.immutable.List.foreach(List.scala:381)
  at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35)
  at scala.collection.mutable.ListBuffer.foreach(ListBuffer.scala:45)
  at scala.collection.TraversableLike$class.map(TraversableLike.scala:245)
  at scala.collection.AbstractTraversable.map(Traversable.scala:104)
  ... 43 elided

1 个答案:

答案 0 :(得分:0)

好吧,我不确定你如何处理没有“toto”键的对象,但也许你可以尝试这样的事情:

val jsonValues = json.as[JsArray].value

jsonValues.map(_.transform(transformer)).zip(jsonValues).foldLeft(JsArray())
{
  case (array, (transformResult, originalObject)) =>
    transformResult match {
      case JsSuccess(newValue, _) => array :+ newValue
      case err: JsError           => array :+ originalObject
    }
}

结果是:

play.api.libs.json.JsArray = [{"toto":3},{"toto":3},{"tata":2}]