Hocon: Read an array of objects from a configuration file Hocon: Read an array of objects from a configuration file json json

Hocon: Read an array of objects from a configuration file


The following works for me in Play 2.1.2 (I don't have a .maybeApplication on my play.Play object though, and I'm not sure why you do):

import play.Playimport scala.collection.JavaConversions._case class Project(name: String, url: String)val projectList: List[Project] = {  val projs = Play.application.configuration.getConfigList("projects") map { p =>     Project(p.getString("name"), p.getString("url")) }  projs.toList}println(projectList)

Giving output:

List(Project(SO,http://stackoverflow.com/), Project(google,http://google.com))

There's not a whole lot different, although I don't get lost in a whole lot of Option instances either (again, different from the API you seem to have).

More importantly, getConfigList seems to be a closer match for what you want to do, since it returns List[play.Configuration], which enables you to specify types on retrieval instead of resorting to casts or .toString() calls.


What are you trying to accomplish with this part y.toList.map{z =>? If you want a collection of Project as the result, why not just do:

val simpleConfig = x.configration.getObjectList("projects").map{y =>   Project(y.get("name").toString, y.get("url").toString)}

In this case, the map operation should be taking instances of ConfigObject which is what y is. That seems to be all you need to get your Project instances, so I'm not sure why you are toListing that ConfigObject (which is a Map) into a List of Tuple2 and then further mapping that again.


If a normal HOCON configuration then similar to strangefeatures answer this will work

import javax.inject._import play.api.Configurationtrait Barfoo {  def configuration: Configuration       def projects = for {    projectsFound <- configuration.getConfigList("projects").toList    projectConfig <- projectsFound    name <- projectConfig.getString("name").toList    url  <- projectConfig.getString("url").toList  } yield Project(name,url)}class Foobar @Inject() (val configuration: Configuration) extends Barfoo

(Using Play 2.4+ Injection)