如何获得PureConfig将JSON反序列化为JValue字段?

我的配置的一部分包含任意JSON。我想将该JSON反序列化为JValue以便以后处理。

但是,ConfigSource.load抱怨找不到type键。

测试代码:

import org.json4s.JsonAST.JValue
import pureconfig.ConfigReader.Result
import pureconfig._
import pureconfig.generic.auto._

object PureConfig2JValue extends App {
  case class Config(json: JValue)

  val source: ConfigObjectsource = ConfigSource.string("{ \"json\": { \"test\": \"test\" } }")

  val loadedSource: Result[Config] = source.load[Config]

  println(loadedSource)
}

输出:

Left(ConfigReaderFailures(ConvertFailure(KeyNotFound(type,Set()),None,json),List()))

如何使PureConfig反序列化为JValue?

更新

我将Gagandeep的答案修改为我的较早版本的PureConfig:

implicit val configReader: ConfigReader[JValue] = new ConfigReader[JValue] {
  override def from(cur: ConfigCursor): Either[ConfigReaderFailures,JValue] =
    cur.asString match {
      case Right(jsonString: String) => Right(parse(jsonString))
      case Left(configReaderFailures: ConfigReaderFailures) => Left(configReaderFailures)
    }
}

它更改了错误消息,我认为这是一个进步:

Left(ConfigReaderFailures(ConvertFailure(WrongType(OBJECT,Set(STRING)),List()))

PureConfig似乎在某个地方需要一个String,但是找到了Object。我不确定断开连接的位置。我正在使用cur.asString以确保该项目以其适当的类型返回。

更新2:

这可能不是最可靠的解决方案,但它适用于我的测试用例:

implicit val configReader: ConfigReader[JValue] = new ConfigReader[JValue] {
  override def from(cur: ConfigCursor): Either[ConfigReaderFailures,JValue] = {
    Right(
      // Parse PureConfig-rendered JSON.
      parse(
        // Render config as JSON.
        cur.value.render(ConfigRenderOptions.concise.setJson(true))
      )
    )
  }
}
yww5491012 回答:如何获得PureConfig将JSON反序列化为JValue字段?

JValue不是类,元组,案例类或密封特性,因此宏无法为其生成自动派生。为此定义一个读者应该会有所帮助。

import org.json4s._
import org.json4s.native.JsonMethods._

implicit val configReader = new ConfigReader[JValue] {
    override def from(cur: ConfigCursor): Result[JValue] = cur.asString.map(parse)
}
本文链接:https://www.f2er.com/3137656.html

大家都在问