使用 Circe 解析 Json 中的自定义键

问题描述

我写了这段代码

import io.circe._,io.circe.generic.auto._,io.circe.parser._,io.circe.syntax._,io.circe.generic.extras._
implicit val config: Configuration = Configuration.default
case class Company(name: String)
case class Quote(average: Double)
case class Stats(price: Double)
@ConfiguredJsonCodec case class Bulk(company: Company,@JsonKey("advanced-stats") stats: Stats,quote: Quote)
val input = """{"AAPL": {"company": {"name": "Apple"},"advanced-stats": {"price":10},"quote": {"average":10}}}"""
val parsed = decode[Map[String,Bulk]](input)

当我尝试在 ammonite 中执行此操作时出现错误

cmd5.sc:1: macro annotation could not be expanded (you cannot use a macro annotation in the same compilation run that defines it)
@ConfiguredJsonCodec case class Bulk(company: Company,quote: Quote)

当我将此代码复制粘贴到文件中并尝试编译它时,它会出现编译错误

could not find Lazy implicit value of type io.circe.generic.extras.codec.ConfiguredAsObjectCodec

编辑:感谢下面的答案,代码开始在菊石上工作。当我将其复制粘贴到 Scala 文件中时,它仍然无法编译。我用谷歌搜索并将代码更改为

object DefaultValues {
  implicit val useDefaultValues = Configuration.default.withDefaults
}

import DefaultValues._
@ConfiguredJsonCodec
case class Bulk(
    company: Company,quote: Quote
)

但它仍然说

could not find Lazy implicit value of type io.circe.generic.extras.codec.ConfiguredAsObjectCodec[Bulk]

解决方法

您是否启用了宏注释? Scala 2.13 需要您可以在 Ammonite 中启用的标志:

interp.configureCompiler(_.settings.YmacroAnnotations.value = true)

在使用 Scala 2.12 及更早版本的 Ammonite 的早期版本中,您必须使用

// replace with Scala version appropriate for your Ammonite
//                                             \/
import $plugin.$ivy.`org.scalamacros:paradise_2.12.11:2.1.1`

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...