[英]Parse a JSON FILE in Scala(2.10.1) using Play
我是scala的一名新手,我在這里要做的就是使用scala解析一個JSON文件,然后將其打印出來。 我在編譯時遇到無法解決的錯誤。 在此先感謝您的任何幫助。 PFB scala代碼,SBT文件,JSON文件和錯誤:
json_example.scala
import scala.io.Source
import play.api.libs.json._
import play.api.libs.json._
object Test extends App {
val line :String = "Foo";
val filename = "users.json"
for (line <- Source.fromFile(filename).getLines().mkString) {
println(line);
val json: JsValue = Json.parse(line);
}
}
JSON文件( users.json )
{"users":[
{"ID":"1","firstName":"John", "lastName":"Doe"},
{"ID":"2","firstName":"Anna", "lastName":"Smith"},
{"ID":"3","firstName":"Peter", "lastName":"Jones"}
{"ID":"1","firstName":"Stewie", "lastName":"Doe"},
{"ID":"2","firstName":"Chris", "lastName":"Smith"},
{"ID":"3","firstName":"Louis", "lastName":"Jones"}
{"ID":"2","firstName":"Brian", "lastName":"Smith"},
{"ID":"3","firstName":"Meg", "lastName":"Jones"}
]}
SBT文件(simple.sbt)
lazy val root = (project in file(".")).
settings(
name := "JSON_GRAPHX",
version := "1.0",
scalaVersion := "2.10.1",
libraryDependencies ++= Seq("com.github.scala-incubator.io" %% "scala-io-file" % "0.4.2",
"com.typesafe.play" %% "play-json" % "2.3.4"),
resolvers += "Typesafe Repo" at "http://repo.typesafe.com/typesafe/releases/"
)
錯誤
[info] Set current project to JSON_GRAPHX (in build file:/F:/Graphx_app/JSON_GRAPHX/)
[info] Compiling 1 Scala source to F:\Graphx_app\JSON_GRAPHX\target\scala-2.10\classes...
[error] F:\Graphx_app\JSON_GRAPHX\json_example.scala:15: overloaded method value parse with alternatives:
[error] (input: Array[Byte])play.api.libs.json.JsValue <and>
[error] (input: String)play.api.libs.json.JsValue
[error] cannot be applied to (Char)
[error] val json: JsValue = Json.parse(line);
[error] ^
[error] one error found
[error] (compile:compileIncremental) Compilation failed
[error] Total time: 4 s, completed Aug 18, 2016 8:51:22 PM
要構建JSON對象,您可以直接在mkString
返回的String
調用parse
方法。 就像是:
val json = Json.parse(Source.fromFile(filename).getLines().mkString)
通過做:
for (line <- Source.fromFile(filename).getLines().mkString)
實際上,您正在遍歷Json String的所有字符-這就是為什么您收到無法將parse
方法應用於Char的錯誤的原因。
擁有JSON對象后,您可以將其縮小打印:
println(Json.stringify(json))
或者您可以以可讀格式打印它:
println(Json.prettyPrint(son))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.