将Typesafe配置解析为案例类

问题描述 投票:2回答:1

什么是解析的拟合案例类:

input {
    foo {
      bar = "a"
      baz = "b"
    }

    bar {
      bar = "a"
      baz = "c"
      other= "foo"
    }
}

通过https://github.com/kxbmap/configs从类型安全的HOCON配置?

怎么能通过ADT读取?看看他们的例子我不知道如何构建一个类层次结构,其中一些类具有不同数量的字段 - 但可以继承一些。

sealed trait Tree
case class Branch(value: Int, left: Tree, right: Tree) extends Tree
case object Leaf extends Tree

我的样本在这里:

import at.tmobile.bigdata.utils.config.ConfigurationException
import com.typesafe.config.ConfigFactory
import configs.syntax._

val txt =
  """
    |input {
    |    foo {
    |      bar = "a"
    |      baz = "b"
    |      type = "foo"
    |    }
    |
    |    bar {
    |      bar = "a"
    |      baz = "c"
    |      other= "foo"
    |      type="bar"
    |    }
    |}
  """.stripMargin

val config = ConfigFactory.parseString(txt)
config

sealed trait Input{ def bar: String
  def baz:String }
case class Foo(bar: String, baz: String) extends Input
case class Bar(bar:String, baz:String, other:String)extends Input

config.extract[Input].toEither match {
  case Right(s) => s
  case Left(l) =>
    throw new ConfigurationException(
      s"Failed to start. There is a problem with the configuration: " +
        s"${l.messages.foreach(println)}"
    )
}

失败了:

No configuration setting found for key 'type'
scala adt case-class typesafe-config
1个回答
1
投票

如果input配置将始终由2字段组成(如示例txt值;即只是foobar),那么你可以这样做:

val txt =
  """
    |input {
    |    foo {
    |      bar = "a"
    |      baz = "b"
    |      type = "foo"
    |    }
    |
    |    bar {
    |      bar = "a"
    |      baz = "c"
    |      other = "foo"
    |      type = "bar"
    |    }
    |}
  """.stripMargin

sealed trait Input {
  def bar: String
  def baz: String
}
case class Foo(bar: String, baz: String) extends Input
case class Bar(bar: String, baz: String, other:String) extends Input

case class Inputs(foo: Foo, bar: Bar)

val result = ConfigFactory.parseString(txt).get[Inputs]("input")
println(result)

输出:

Success(Inputs(Foo(a,b),Bar(a,c,foo)))

--

如果您打算设置一系列通用输入,那么您应该在配置中反映这一点并解析Seq[Input]

val txt =
  """
    |inputs = [
    |    {
    |      type = "Foo"
    |      bar = "a"
    |      baz = "b"
    |    }
    |
    |    {
    |      type = "Bar"
    |      bar = "a"
    |      baz = "c"
    |      other= "foo"
    |    }
    |]
  """.stripMargin

sealed trait Input {
  def bar: String
  def baz: String
}
case class Foo(bar: String, baz: String) extends Input
case class Bar(bar: String, baz: String, other: String) extends Input

val result = ConfigFactory.parseString(txt).get[Seq[Input]]("inputs")
println(result)    

输出:

Success(Vector(Foo(a,b), Bar(a,c,foo)))
© www.soinside.com 2019 - 2024. All rights reserved.