我是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
答案 0 :(得分:2)
要构建JSON对象,您可以直接在{
"localTrain": "T7",
"TC": "2",
"TimeSheet": [
["01", "London", "BXP", "T7", "1632", "1640"],
["01", "London", "BXP", "T7", "1632", "1640"],
["02", "Shanghai", "QWE", "T7", "1200", "1240"],
["02", "Shanghai", "QWE", "T7", "1200", "1240"],
["03", "LosAngeles", "DFG", "T7", "1300", "1340"],
["03", "LosAngeles", "DFG", "T7", "1300", "1340"],
["04", "NewDelhi", "VGH", "T7", "1400", "1440"],
["04", "NewDelhi", "VGH", "T7", "1400", "1440"],
["05", "Sydney", "SAW", "T7", "1500", "1540"],
["04", "NewDelhi", "VGH", "T7", "1400", "1440"],
["06", "Tokyo", "SAT", "T7", "1600", "1640"],
["06", "Tokyo", "SAT", "T7", "1600", "1640"],
["07", "Seoul", "BBT", "T7", "1700", "1740"],
["07", "Seoul", "BBT", "T7", "1700", "1740"],
["08", "CapeTown", "OOP", "T7", "1800", "1840"],
["08", "CapeTown", "OOP", "T7", "1800", "1840"],
]
}
返回的parse
中调用String
方法。类似的东西:
mkString
通过做:
val json = Json.parse(Source.fromFile(filename).getLines().mkString)
您实际上正在迭代Json字符串的所有字符 - 这就是您收到for (line <- Source.fromFile(filename).getLines().mkString)
方法无法应用于Char的错误的原因。
获得JSON对象后,可以将其缩小打印:
parse
或者您可以以可读格式打印:
println(Json.stringify(json))