无法获取pureconfig来反序列化嵌套的案例类

时间:2019-03-20 17:29:00

标签: scala nested deserialization pureconfig

我正在尝试获取嵌套的case类以使用pureconfig反序列化,但是代码无法编译。我有以下内容:

import com.typesafe.config.{Config, ConfigFactory}
import pureconfig.error.ConfigReaderFailures
import pureconfig.generic.ProductHint
import pureconfig.generic.semiauto._
import pureconfig.{CamelCase, ConfigFieldMapping}

class ClassAReader {
  implicit def classAHint = ProductHint[ClassA](ConfigFieldMapping(CamelCase, CamelCase))
  implicit def classBHint = ProductHint[ClassB](ConfigFieldMapping(CamelCase, CamelCase))

  implicit val classAReader = deriveReader[ClassA]
  implicit val classBReader = deriveReader[ClassB]

  def read(config: Config): ClassA = pureconfig.loadConfig[ClassA](config.getConfig("foo")).fold((a: ConfigReaderFailures) => throw new Exception(), conf => conf)

  val config = ConfigFactory.parseString("""{ a: { one: 1, two: "foo" }, b: { one: 2, two: "bar" }, 42 }""")
  val reader = new ClassAReader

  reader.read(config)
}

case class ClassA(a: ClassB, b: ClassB, other: Int)

case class ClassB(one: Int, two: String)

但是我遇到了编译问题。有人知道我在做什么错吗?

1 个答案:

答案 0 :(得分:2)

您应该总是注释隐式定义,尤其是在这样的情况下,ClassA的读者推导取决于ClassB的读者,等等。正常工作:

import com.typesafe.config.{Config, ConfigFactory}
import pureconfig.ConfigReader
import pureconfig.error.ConfigReaderFailures
import pureconfig.generic.ProductHint
import pureconfig.generic.semiauto._
import pureconfig.{CamelCase, ConfigFieldMapping}

class ClassAReader {
  implicit def classAHint: ProductHint[ClassA] =
    ProductHint[ClassA](ConfigFieldMapping(CamelCase, CamelCase))
  implicit def classBHint: ProductHint[ClassB] =
    ProductHint[ClassB](ConfigFieldMapping(CamelCase, CamelCase))

  implicit val classAReader: ConfigReader[ClassA] = deriveReader[ClassA]
  implicit val classBReader: ConfigReader[ClassB] = deriveReader[ClassB]

  def read(config: Config): Either[ConfigReaderFailures, ClassA] =
    pureconfig.loadConfig[ClassA](config)
}

case class ClassA(a: ClassB, b: ClassB, other: Int)
case class ClassB(one: Int, two: String)

然后:

scala> val config = ConfigFactory.parseString(
     |   """{ a: { one: 1, two: "foo" }, b: { one: 2, two: "bar" }, other: 42 }"""
     | )
config: com.typesafe.config.Config = Config(SimpleConfigObject({"a":{"one":1,"two":"foo"},"b":{"one":2,"two":"bar"},"other":42}))

scala> val reader = new ClassAReader
reader: ClassAReader = ClassAReader@589da48f

scala> reader.read(config)
res1: Either[pureconfig.error.ConfigReaderFailures,ClassA] = Right(ClassA(ClassB(1,foo),ClassB(2,bar),42))

(请注意,我还必须将read调用移出该类,否则构造函数将自行调用,您将得到Stack Overflow。我还修复了该示例,以便可以对其进行解码。 )