我的配置的一部分包含任意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))
)
)
}
}