[英]Retrieving list of objects from application.conf
I have the following entry in Play for Scala application.conf
: 我在Play for Scala
application.conf
有以下条目:
jobs = [
{number: 0, dir: "/dir1", name: "General" },
{number: 1, dir: "/dir2", name: "Customers" }
]
I want to retrieve this list of objects in a Scala program: 我想在Scala程序中检索此对象列表:
val conf = ConfigFactory.load
val jobs = conf.getAnyRefList("jobs").asScala
println(jobs)
this prints 此打印
Buffer({number=0, name=General, dir=/dir1}, {number=1, name=Customers, dir=/dir2})
But how to convert the result to actual Scala objects? 但是如何将结果转换为实际的Scala对象?
Try this one: 试试这个:
case class Job(number: Int, dir: String, name: String)
object Job {
implicit val configLoader: ConfigLoader[List[Job]] = ConfigLoader(_.getConfigList).map(
_.asScala.toList.map(config =>
Job(
config.getInt("number"),
config.getString("dir"),
config.getString("name")
)
)
)
}
Then from Confugutation DI Configuration.get[List[Job]]("jobs")
然后从
Configuration.get[List[Job]]("jobs")
DI Configuration.get[List[Job]]("jobs")
.get Configuration.get[List[Job]]("jobs")
Here is a Config
object which will extract data from a config file into a type that you specify. 这是一个
Config
对象,它将数据从配置文件提取为您指定的类型。
Usage: 用法:
case class Job(number: Int, dir: String, name: String)
val jobs = Config[List[Job]]("jobs")
Code: 码:
import com.typesafe.config._
import org.json4s._
import org.json4s.jackson.JsonMethods._
object Config {
private val conf = ConfigFactory.load()
private val jData = parse(conf.root.render(ConfigRenderOptions.concise))
def apply[T](name: String)(implicit formats: Formats = DefaultFormats, mf: Manifest[T]): T =
Extraction.extract(jData \\ name)(formats, mf)
}
This will throw an exception if the particular config object does not exist or does not match the format of T
. 如果特定的配置对象不存在或与
T
的格式不匹配,则将引发异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.