Scala 如何递归地构建json镜头
我正在使用并尝试递归搜索Json对象的分支,类似于:Scala 如何递归地构建json镜头,scala,Scala,我正在使用并尝试递归搜索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)
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比较陌生,不知道如何解决这个问题。这应该可以:
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
}
}
测试:
我不知道是否有像空镜头这样的东西…我认为问题归结为1如何将镜头指定为参数类型,2如何指定空镜头。任何人
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":{}}