Scala Collection Traverse in Scala

I would like to cross the collection derived from the Scala JSON toolkit on github. The problem is that JsonParser returns "Any", so I wonder how I can avoid the following error:

"The foreach value is not a member of Any."

val json = Json.parse(urls)

for(l <- json) {...}

object Json {
  def parse(s: String): Any = (new JsonParser).parse(s)
}
+3
source share
3 answers

You will need to perform pattern matching to traverse the structures returned from the analyzer.

/*
 * (untested)
 */
def printThem(a: Any) {
  a match {
    case l:List[_] => 
      println("List:")
      l foreach printThem
    case m:Map[_, _] =>
      for ( (k,v) <- m ) {
        print("%s -> " format k)
        printThem(v)
      }
    case x => 
      println(x)
  }
val json = Json.parse(urls)
printThem(json)
+6
source

You can have more luck with lift-json parsing, available at: http://github.com/lift/lift/tree/master/framework/lift-base/lift-json/

DSL, ( ) Lift.

+4

If you are sure that in all cases there will be only one type, you can create the following composition:

for (l <- json.asInstanceOf[List[List[String]]]) {...}

Otherwise, perform pattern matching for all expected cases.

0
source

Source: https://habr.com/ru/post/1771513/


All Articles