我使用json-lenses并尝试递归搜索Json对象的分支,类似于:
import spray.json._
import spray.json.lenses.JsonLenses._
import DefaultJsonProtocol._
import scala.annotation.tailrec
@tailrec
def getLens(json: JsValue, lensAcc: Lens = Nil, depth: Int = 0): Lens = {
if (depth > 10) {
throw new IllegalStateException("Recursive search for lens exhausted.")
}
val thisLens = lensAcc / 'rec / element(0)
json.extract[JsObject](thisLens / 'properties.?) match {
case None => getLens(json, thisLens, depth + 1)
case _ => thisLens
}
}
val json = """{"rec": [{"rec": [{"properties": {}}]}]}""".parseJson.asJsObject
val myLens = getLens(json)
这是不对的。我对Scala比较陌生,无法弄清楚如何解决这个问题。
答案 0 :(得分:0)
这应该有效:
def nextLens = 'rec / element(0)
@scala.annotation.tailrec
final def getLens(json: JsObject, lensAcc: Lens[Id] = nextLens, depth: Int = 0): Lens[Id] = {
if (depth > 10) {
throw new IllegalStateException("Recursive search for lens exhausted.")
}
json.extract[JsObject](lensAcc / 'properties.?) match {
case None => getLens(json, lensAcc / nextLens, depth + 1)
case _ => lensAcc
}
}
测试:
scala> val json = JsonParser("""{"rec": [{"rec": [{"properties": {}}]}]}""").asJsObject
json: spray.json.JsObject = {"rec":[{"rec":[{"properties":{}}]}]}
scala> getLens(json)
res6: spray.json.lenses.Lens[spray.json.lenses.Id] = spray.json.lenses.JsonLenses$$anon$1@448cd79c
scala> json.extract[JsObject](res6)
res9: spray.json.JsObject = {"properties":{}}
我不知道是否有空镜头......