Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何让PureConfig将JSON反序列化为JValue字段?_Json_Scala_Deserialization_Json4s_Pureconfig - Fatal编程技术网

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

如何让PureConfig将JSON反序列化为JValue字段?,json,scala,deserialization,json4s,pureconfig,Json,Scala,Deserialization,Json4s,Pureconfig,我的配置的一部分包含任意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 { cas

我的配置的一部分包含任意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)),None,json),List()))
PureConfig似乎希望在某个地方有一个字符串,但却找到了一个对象。我不确定断开的地方在哪里。我正在使用
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))
      )
    )
  }
}

JValue不是类、元组、case类或密封特征,因此宏无法为其生成自动派生。为它定义一个阅读器应该会有所帮助

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)
}

谢谢,看起来是个很好的答案!我更新了我的问题,以显示我在尝试您的代码后遇到的新障碍。请让我知道,如果你看到任何明显的解决方案。接受,因为这使我在正确的道路上。我使用的代码在更新的问题中。注意:Json4s是!