2014-01-19 64 views
1

我有一个JSON对象"{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true}"和代码:JSON解析在斯​​卡拉与scala.util.parsing.json

println(request.getParameter("content"))//{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true} 
val result = scala.util.parsing.json.JSON.parseFull(request.getParameter("content")) 
result match { 
    case Some(e) => { println(e); //output: Map(name -> OZKA, monthRevenue -> 1000.75, developer -> true, birthDate -> 1981-02-08T20:00:00.000Z, id -> 1.0) 
    e.foreach((key: Any, value: Any) => {println(key + ":" + value)}) 
    } 
    case None => println("Failed.") 
} 

,当我尝试调用地图或的foreach函数,编译器会引发错误“值的foreach不是Any的成员“。任何人都可以建议我的方式,我怎么可以解析此JSON字符串,其转换为斯卡拉类型

回答

4

你得到,因为编译器无法知道的e的类型Some(e)图案的方式造成的错误,其作为infered Any。并且Any没有foreach方法。您可以通过明确指定e的类型作为Map来解决此问题。

其次,对于一个地图foreach有签名foreach(f: ((A, B)) ⇒ Unit): Unit。匿名函数的参数是一个包含键和值的元组。

尝试这样:

println(request.getParameter("content"))//{"id":1,"name":"OZKA","birthDate":"1981-02-08T20:00:00.000Z","monthRevenue":1000.75,"developer":true} 
val result = scala.util.parsing.json.JSON.parseFull(request.getParameter("content")) 
result match { 
    case Some(e:Map[String,String]) => { 
    println(e); //output: Map(name -> OZKA, monthRevenue -> 1000.75, developer -> true, birthDate -> 1981-02-08T20:00:00.000Z, id -> 1.0) 
    e.foreach { pair => 
     println(pair._1 + ":" + pair._2)   
    } 
    } 
    case None => println("Failed.") 
} 
+0

谢谢你,它的工作! 'e.foreach {pair:Tuple2 [String,String] => println(pair._1 +“:”+ pair._2) } }' – OZKA

+0

感谢这很棒! – tesnik03

+0

我使用了相同的模式来捕捉解析失败,但编译器返回以下警告:“类型模式Map [String,String]中的非变量类型参数String未被选中,因为它被擦除消除” – dieHellste

0

您可以访问键和值在任何JSON为:

import scala.util.parsing.json.JSON 
import scala.collection.immutable.Map 

val jsonMap = JSON.parseFull(response).getOrElse(0).asInstanceOf[Map[String,String]] 
val innerMap = jsonMap("result").asInstanceOf[Map[String,String]] 
innerMap.keys //will give keys 
innerMap("anykey") //will give value for any key anykey