如何使用Play with Scala

时间:2015-12-17 12:20:46

标签: json scala playframework

我需要在我的控制器中加载一个包含城市列表的JSON文件,然后将其传递给视图。< / p>

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

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

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

我们非常感谢代码片段以及如何在答案中执行此操作的示例! :)

非常感谢你!

4 个答案:

答案 0 :(得分:18)

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

Json.parse接受一些不同的参数类型,其中一种是import UIKit import CoreBluetooth class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralManagerDelegate { var centralManager:CBCentralManager! var peripheralManager:CBPeripheralManager = CBPeripheralManager() let uuid:CBUUID = CBUUID(string: "DCEF54A2-31EB-467F-AF8E-350FB641C97B") override func viewDidLoad() { super.viewDidLoad() self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil) self.centralManager = CBCentralManager(delegate: self, queue: nil) let advertisingData = [CBAdvertisementDataLocalNameKey:"my-peripheral", CBAdvertisementDataServiceUUIDsKey: uuid] peripheralManager.startAdvertising(advertisingData) centralManager.scanForPeripheralsWithServices([uuid], options: [ CBCentralManagerScanOptionAllowDuplicatesKey : true]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) { print("started advertising") print(peripheral) } func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) { print("peripheral discovered") print("peripheral: \(peripheral)") print("advertisement: \(advertisementData)") if let data = advertisementData["kCBAdvDataServiceData"] { print("found advert data: \(data)") } print("RSSI: \(RSSI)") } func startAdvert(){ let advertisingData = [CBAdvertisementDataLocalNameKey:"my-peripheral", CBAdvertisementDataServiceUUIDsKey: uuid] peripheralManager.startAdvertising(advertisingData) } func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) { print("peripheral disconnected") print("peripheral: \(peripheral)") } func centralManagerDidUpdateState(central: CBCentralManager) { print("central state updated") print(central.description) if central.state == .PoweredOff { print("bluetooth is off") } if central.state == .PoweredOn { print("bluetooth is on") centralManager.scanForPeripheralsWithServices(nil, options: [ CBCentralManagerScanOptionAllowDuplicatesKey : true]) startAdvert() } if central.state == .Unsupported { print("bluetooth is unsupported on this device") } } func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) { print("peripheral state updated") print("\(peripheral.description)") } }

InputStream

P.S。如果您无法在书面文档中找到您正在寻找的内容,那么API Docs就是一个很好的起点。

答案 1 :(得分:12)

以下是我设法解决的方法:

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

感谢您的帮助! :)

答案 2 :(得分:3)

从Play 2.6开始,环境采用getExistingFilegetFileresourceresourceAsStream方法,例如:

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

(注意,在这种情况下, data.json 位于 conf 文件夹中)

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

答案 3 :(得分:0)

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

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

使用上一个函数只是传递filename路径的问题。量身定制要与Play搭配使用的文件,您可能需要将文件放置在资源文件夹中,并启用它,您需要将其放置在build.sbt文件中:

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

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

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