我想我可能会遗漏list-json xpath架构中的一些基本内容.我能够提取和遍历列表的最流畅的方式如下所示.有人可以告诉我一个更好的技术:
class Example { @Test def traverseJsonArray() { def myOperation(kid:JObject) = println("kid="+kid) val json = JsonParser.parse(""" { "kids":[ {"name":"bob","age":3},{"name":"angie","age":5},]} """) val list = ( json \\ "kids" ).children(0).children for ( kid <- list ) myOperation(kid.asInstanceOf[JObject]) } }
解决方法
如果可能的话,你应该升级到Lift JSON 2.3-M1(http://www.scala-tools.org/repo-releases/net/liftweb/lift-json_2.8.1/2.3-M1/).它包含两个重要的改进,另一个影响路径表达式.
使用2.3,路径表达式永远不会返回JField,而是直接返回JFields的值.之后,您的示例将如下所示:
val list = (json \ "kids").children for ( kid <- list ) myOperation(kid.asInstanceOf[JObject])
Lift JSON提供了几种样式来解析JSON中的值:路径表达式,查询理解和案例类提取.可以混合和匹配这些样式,以获得我们经常做的最好的结果.为了完整起见,我将为您提供上述示例的一些变体,以更好地直观了解这些不同的风格.
// Collect all JObjects from 'kids' array and iterate val JArray(kids) = json \ "kids" kids collect { case kid: JObject => kid } foreach myOperation // Yield the JObjects from 'kids' array and iterate over yielded list (for (kid@JObject(_) <- json \ "kids") yield kid) foreach myOperation // Extract the values of 'kids' array as JObjects implicit val formats = DefaultFormats (json \ "kids").extract[List[JObject]] foreach myOperation // Extract the values of 'kids' array as case classes case class Kid(name: String,age: Int) (json \ "kids").extract[List[Kid]] foreach println // Query the JSON with a query comprehension val ks = for { JArray(kids) <- json kid@JObject(_) <- kids } yield kid ks foreach myOperation