2016-08-19 49 views
0

我是scala中的一个完整的新手,我想在这里做的只是使用scala简单解析并打印相同的JSON文件。我在编译我无法解决的问题时遇到了一个错误。提前感谢您的帮助。 PFB的Scala代码,SBT文件,JSON文件和错误:在Scala中使用Play解析JSON文件(2.10.1)

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文件(简单.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 

回答

2

要构建JSON对象,你可以直接通过mkString返回String调用parse方法。喜欢的东西:

val json = Json.parse(Source.fromFile(filename).getLines().mkString) 

这样做:

for (line <- Source.fromFile(filename).getLines().mkString) 

你实际上是遍历JSON字符串的所有字符 - 这就是为什么你得到了parse方法不能适用于字符错误。

一旦你的JSON对象,你可以打印精缩:

println(Json.stringify(json)) 

或者您也可以以可读格式打印:

println(Json.prettyPrint(son)) 
+0

这是一个完美的解决方案。想知道为什么这不被接受 – Rakshith

+0

它的工作。非常感谢@virsox的帮助。回复较晚,抱歉。 – Anwesha