json - 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 代码,如果是这样,是否有更好的方法来做我想做的事?
解决方案
推荐阅读
- r - R中的runif(或者我)有什么问题?
- .net - 当所有事情都可以在 Aspnet MVC 中的 Post 中完成时,Put 方法的需要是什么?
- linux - 在 perl 套接字编程中,如何从客户端发送数据并从服务器接收数据以及如何获取客户端进程数和客户端 ID?
- django - 如何在 Django 视图中显示来自服务器的 pdf?
- java - 如何在 java 中解决 NoSuchElementException
- asp.net-core - 在 IIS Express 上具有属性路由的 ASP.Net 核心在发布时会出现 503 错误
- apache-camel - Apache Camel Mail 组件接收器示例不起作用
- django - 了解 django 注释
- r - 如何根据另一列的条件在列中应用操作
- r - 如何在后端使用 Impala 连接修复 dbWriteTable“错误:无法取消引用 dbo.test_cars”?