如何将json文件的记录转换为scala中的List

时间:2016-09-14 09:28:07

标签: scala

我在Scala上做了一些动手

我有一个名为simple.json的json文件

"employees":[
{"firstName":"John", "lastName":"Doe"}, 
{"firstName":"Anna", "lastName":"Smith"}, 
{"firstName":"Peter","lastName":"Jones"}
]

我想从中读取此json文件并将此值的值保存在scala List

预期产出:

  List("John|Doe", "Anna|Smith", "Peter|Jones")

我无法继续使用scala文件

package pack1
import scala.io.Source
import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.ParseException;
import org.json.simple.parser.JSONParser;
   object ss {

    def main(args: Array[String]): Unit = {       
    val mySource=Source.fromFile("C:\\inputfiles\\simple.json").getLines().mkString
    println(mySource)
    val parser = new JSONParser();
    val jArray = parser.parse(mySource);


 }

 }

如何继续使用代码获取预期的输出

1 个答案:

答案 0 :(得分:1)

使用libraryDependencies ++= Seq("com.typesafe.play" %% "play-json" % "2.5.4")

如果您正在使用sbt项目。将以下行添加到项目中的依赖项。

build.sbt

val lines = Source.fromFile("<file-path>").getLines.mkString
val json = Json.parse("{" + lines.replaceAll("""\n""", "").trim + "}")
val list = (json \ "employees").as[List[JsValue]]
           .map(name => s"""${(name \ "firstName").as[String]}|${(name \ "lastName").as[String]}""")

源代码

scala>  import play.api.libs.json._

scala> val str = """ {"employees" : [ {"firstName":"John", "lastName":"Doe"} ] }""".trim
str: String = {"employees" : [ {"firstName":"John", "lastName":"Doe"} ] }

scala> val json = Json.parse(str)
json: play.api.libs.json.JsValue = {"employees":[{"firstName":"John","lastName":"Doe"}]}

scala> val list = (json \ "employees").as[List[JsValue]].map(name => s"""${(name \ "firstName").as[String]}|${(name \ "lastName").as[String]}""")
list: List[String] = List(John|Doe)

Scala REPL

val str = """
"employees":[
              {"firstName":"John", "lastName":"Doe"}, 
              {"firstName":"Anna", "lastName":"Smith"}, 
              {"firstName":"Peter","lastName":"Jones"}
            ] """.stripMargin

请注意,下面的字符串不是有效的json

{ }

这必须包含在Json.parse val validJsonStr = "{" + str + "}" 内,以便正确解析。

<uap:Extension Category="windows.appService" StartPage="www\index.html">
    <uap:AppService Name="CommunicationService" />
</uap:Extension>

<desktop:Extension Category="windows.fullTrustProcess" Executable="mywin32app.exe" EntryPoint="Windows.FullTrustApplication" />