如何使用 Play with Scala 加载 JSON 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34334462/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 18:11:07  来源:igfitidea点击:

How to load JSON file using Play with Scala

jsonscalaplayframework

提问by Henrique Ferrolho

I need to load a JSONfile with a list of cities in one of my controllers, in order to pass it to a viewafterwards.

我需要JSON在我的一个控制器中加载一个包含城市列表的文件,以便之后将其传递给视图

I have placed the file here: app/assets/jsons/countriesToCities.json
(By the way: is this an appropriate location, or should I place it somewhere else?)

我把文件放在这里:(app/assets/jsons/countriesToCities.json
顺便说一句:这是一个合适的位置,还是我应该把它放在其他地方?)

I have read the docsand I can see it is possible to create a JsValuefrom a string: https://www.playframework.com/documentation/2.4.x/ScalaJson#Using-string-parsing

我已经阅读了文档,我可以看到可以JsValue从字符串创建一个:https: //www.playframework.com/documentation/2.4.x/ScalaJson#Using-string-parsing

I want to create a JsValuein a similar fashion. The difference is that I want to load the content from a file, not from a string... I haven't found any code snippet on how to do this, unfortunately.
Do I have to use something else to read the file into a string and only then use the parse method on that string?

我想以JsValue类似的方式创建一个。不同之处在于我想从文件中加载内容,而不是从字符串中加载...不幸的是,我还没有找到任何关于如何执行此操作的代码片段。
我是否必须使用其他方法将文件读入字符串,然后才对该字符串使用 parse 方法?

Code snippets with examples on how to do this in the answers will be highly appreciated! :)

非常感谢在答案中提供有关如何执行此操作的示例的代码片段!:)

Thank you very much in advance!

非常感谢您提前!

采纳答案by Henrique Ferrolho

Here is how I managed to solve it:

这是我设法解决它的方法:

val source: String = Source.fromFile("app/assets/jsons/countriesToCities.json").getLines.mkString
val json: JsValue = Json.parse(source)

Thanks for the help! :)

谢谢您的帮助!:)

回答by Dylan

Looks like the comment about the possible duplicate is how to read a file from your app/assets folder. My answer is about how to parse Json from a stream. Combine the two and you should be good to go.

看起来关于可能重复的评论是如何从您的 app/assets 文件夹中读取文件。我的答案是关于如何从流中解析 Json。将两者结合起来,你应该很高兴。

Json.parseaccepts a few different argument types, one of which is InputStream.

Json.parse接受几种不同的参数类型,其中之一是InputStream.

val stream = new FileInputStream(file)
val json = try {  Json.parse(stream) } finally { stream.close() }

P.S. When you can't find what you're looking for in the written docs, the API Docsare a good place to start.

PS 当您在书面文档中找不到您要查找的内容时,API 文档是一个不错的起点。

回答by flurdy

From Play 2.6, Environment has the getExistingFile, getFile, resourceand resourceAsStreammethods, E.g.:

从播放2.6,环境有getExistingFilegetFileresourceresourceAsStream方法,例如:

class Something @Inject (environment: play.api.Environment) {
  // ...
  environment.resourceAsStream("data.json") map ( Json.parse(_) )

(Note, in this case data.jsonis inside the conffolder)

(注意,在这种情况下data.jsonconf文件夹中)

https://www.playframework.com/documentation/2.6.x/api/scala/index.html#play.api.Environment

https://www.playframework.com/documentation/2.6.x/api/scala/index.html#play.api.Environment

回答by mkarmona

I usually need few small dictionaries to live in memory in order to build some plain LUTs (LookUp Tables). In order to achieve that I use the following piece of code (please it is worth noting I am using latest Play 2.6):

我通常需要很少的小词典才能保存在内存中,以便构建一些普通的 LUT(查找表)。为了实现这一点,我使用了以下代码(请注意,我使用的是最新的Play 2.6):

def loadJSONFromFilename(filename: String): Option[JsValue] =
  Option(Source.fromFile(filename).mkString)
    .map(Json.parse)

Using the previous function is just a matter of passing a filenamepath. Tailoring this to be used with Play you might need to place your file in a resource folder and to enable it you need to place this in your build.sbtfile:

使用前面的函数只是传递filename路径的问题。调整它以与 Play 一起使用,您可能需要将您的文件放在资源文件夹中,并启用它,您需要将它放在您的build.sbt文件中:

// include resources into the unversal zipped package using sbt dist
mappings in Universal ++= directory(baseDirectory.value / "resources")

Thus, you can use this resource folder this way in your Play class:

因此,您可以在 Play 类中以这种方式使用此资源文件夹:

lazy val lutFilePath: Path = 
  Paths.get(env.rootPath.getAbsolutePath, "resources", "lut.json")
lazy val lutJson = loadJSONFromFilename(lutFilePath.toString)