如何使用 circe "flatten" JSON 表示对象,即从 case class 到它的字符串表示?
How to "flatten" JSON representation of objects using circe i.e., from case class to its string representation?
我有一个我们内部使用的自定义 Date
class:
case class Date(month: Int, day: Int, year: Year)
并这样使用:
case class Person(dateOfBirth: Date)
但是,当我为 Person(Date(12, 20, 1990))
生成 Json 时,我得到如下内容:
{
"dateOfBirth": {
"month": 12,
"day": 20,
"year": 1990
}
}
我想得到的是这样的:
{ "dateOfBirth": "12-20-2990" } // or any custom format
是否可以 "flatten" 自定义大小写 classes 以便将它们视为一个值而不是展开?我试过这样的事情,它导致 WhosebugError
:
implicit val dateEncoder: Encoder[Date] = (date: Date) => {
Json.fromString(s"${date.month}-${date.dayOfMonth}-${date.year}")
}
UPDATE:这个错误似乎与编码器无关——它恰好在添加这个编码器时被触发,但没有强迫我得出结论,这不是正确的方法的编码。我接受了答案,因为它确实正确回答了 "asked" 问题。
这里是"fails"在Date后面加一个的编码器:
implicit val myEncoder: Encoder[Vector[MyCaseClass]] = (my: Vector[MyCaseClass]) => {
if (my.nonEmpty) my.asJson else Json.Null
}
我可以将其编码为 Option[Vector[MyCaseClass]]
,但我正在尝试直接编码 Vector 以查看会发生什么...
您可以手动为任何类型编写 encoder/decoder。您似乎需要 Date
:
的新实现
object Date {
implicit val encoder: Encoder[Date] = (date: Date) =>
Json.fromString(s"${date.day}-${date.month}-${date.year}")
implicit val decoder: Decoder[Date] = ??? // if you need this
}
我有一个我们内部使用的自定义 Date
class:
case class Date(month: Int, day: Int, year: Year)
并这样使用:
case class Person(dateOfBirth: Date)
但是,当我为 Person(Date(12, 20, 1990))
生成 Json 时,我得到如下内容:
{
"dateOfBirth": {
"month": 12,
"day": 20,
"year": 1990
}
}
我想得到的是这样的:
{ "dateOfBirth": "12-20-2990" } // or any custom format
是否可以 "flatten" 自定义大小写 classes 以便将它们视为一个值而不是展开?我试过这样的事情,它导致 WhosebugError
:
implicit val dateEncoder: Encoder[Date] = (date: Date) => {
Json.fromString(s"${date.month}-${date.dayOfMonth}-${date.year}")
}
UPDATE:这个错误似乎与编码器无关——它恰好在添加这个编码器时被触发,但没有强迫我得出结论,这不是正确的方法的编码。我接受了答案,因为它确实正确回答了 "asked" 问题。
这里是"fails"在Date后面加一个的编码器:
implicit val myEncoder: Encoder[Vector[MyCaseClass]] = (my: Vector[MyCaseClass]) => {
if (my.nonEmpty) my.asJson else Json.Null
}
我可以将其编码为 Option[Vector[MyCaseClass]]
,但我正在尝试直接编码 Vector 以查看会发生什么...
您可以手动为任何类型编写 encoder/decoder。您似乎需要 Date
:
object Date {
implicit val encoder: Encoder[Date] = (date: Date) =>
Json.fromString(s"${date.day}-${date.month}-${date.year}")
implicit val decoder: Decoder[Date] = ??? // if you need this
}