Pergunta

I have read this topic

Iterate over fields in typesafe config

and made some changes but still don't know how to iterate over conf files in play framework.

  Providers=[{1234 : "CProduct"},
{12345 : "ChProduct"},
{123 : "SProduct"}]

This is my Conf file called providers.conf , the question is how can i iterate over them and create a dropdownbox from them. I would like to take them as map if possible which is [int,string]

I know , i have to take them like

val config = ConfigFactory.load("providers.conf").getConfigList("Providers")

i can the conf file like that but , i should get it from template in order to do that i need to convert it to either hashmap or list or whatever functional.

Cheers,

Foi útil?

Solução 2

Here is my solution for that ,

   val config = ConfigFactory.load("providers.conf").getConfigList("Providers")

    var providerlist = new java.util.ArrayList[model.Provider]
    val providers = (0 until config.size())
    providers foreach {
      count => 
        val iterator = config.get(count).entrySet().iterator()

        while(iterator.hasNext()) {
          val entry = iterator.next()

          val p = new Provider(entry.getKey(), entry.getValue().render())
          providerlist.add(p);
        }
    }
    println(providerlist.get(0).providerId+providerlist.get(0).providerName)
    println(providerlist.get(33).providerId+providerlist.get(33).providerName)

and my provider.class

package model

case class Provider(providerId: String, providerName: String) 

Outras dicas

I'm not sure if this is the most efficient way to do this, but this works:

1) Lets get our config file:

val config = ConfigFactory.load().getConfigList("providers")
scala> config.getConfigList("providers")
res23: java.util.List[_ <: com.typesafe.config.Config] = [Config(SimpleConfigObject({"id":"1234","name":" Product2"})), Config(SimpleConfigObject({"id":"4523","name":"Product1"})), Config(SimpleConfigObject({"id":"432","name":" Product3"}))]

2) For this example introduce Provider entity:

case class Provider(id: String, name: String)

3) Now lets convert list with configs to providers:

import scala.collection.JavaConversions._
providers.map(conf => Provider(conf.getString("id"), conf.getString("name"))).toList
res27: List[Provider] = List(Provider(1234, Product2), Provider(4523,Product1), Provider(432, Product3))

We need explicitly convert it toList, cause by default Java List converts to Buffer.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top