首页 > 解决方案 > Scala Circe JSON 库 - 在示例中理解隐式编码器

问题描述

我正在使用 Scala Circe 库。它似乎非常有用,我想更好地使用它。

我的一个例子如下。

考虑以下代码:

import io.circe.syntax._
import io.circe.{Json, Encoder}
import io.circe.generic.auto._

sealed trait JsonComponent
case class DataSequences(values: Map[String, List[Int]]) extends JsonComponent
case class DataField(data: List[DataSequences], `type`: String) extends JsonComponent

object Example extends App {

  implicit val encodeDataSequences: Encoder[DataSequences] = new Encoder[DataSequences] {
    final def apply(sequence: DataSequences): Json = sequence.values.asJson
  }

  val x = new DataSequences(Map("x" -> List(1, 2, 3), "y" -> List(1, 2, 4)))
  val l = List(DataField(List(x, x), "abc"), DataField(List(x, x), "cde")).asJson

  println(l)
}

这给出了以下输出:

[
  {
    "data" : [
      {
        "x" : [
          1,
          2,
          3
        ],
        "y" : [
          1,
          2,
          4
        ]
      },
      {
        "x" : [
          1,
          2,
          3
        ],
        "y" : [
          1,
          2,
          4
        ]
      }
    ],
    "type" : "abc"
  }
]

但是,如果我注释掉encodeDataSequences编码器定义,我会得到以下内容:

[
  {
    "data" : [
      {
        "x" : [
          1,
          2,
          3
        ],
        "y" : [
          1,
          2,
          4
        ]
      },
      {
        "x" : [
          1,
          2,
          3
        ],
        "y" : [
          1,
          2,
          4
        ]
      }
    ],
    "type" : "abc"
  }
]

所以现在这个“价值观”出现了。我不希望显示“值”字段。我不确定隐式如何在引擎盖下塑造 Json,如果有人能强调正在发生的事情,那将不胜感激。

此外,作为一般的事情,我是否使用该隐式编码器编写惯用的 Circe 代码,如果是这样,是否有更好的方法来做我想做的事?

标签: jsonscalaimplicitcirce

解决方案


推荐阅读