如何为课堂编写circe解码器?
case class KeyValueRow(count: Int, key: String)
其中json包含字段"count“(Int)和一些额外的字符串字段(这个字段的名称可能是不同的,比如"url”、"city“等等)?
{"count":974989,"url":"http://google.com"}
{"count":1234,"city":"Rome"}
我写这封信是为了写任何的编码器/解码器。假设我的课是
case class Demo(
field1: Any
)
然后我试着通过
val myDemo=Demo(field1=None)
print(myDemo.asJson+"\n")
我把编码器译码器定义为
implicit val valueEncoderValue: Encoder[Any] = Encoder.encodeString.contramap[Any](x=>{
x.toString})
implicit val valueDecoderValue: Decoder[Any] =
正如中所指定的,可以将蛇案例转换为Scala中惯用的骆驼案例。我试过了,效果很好。这就是:
implicit lazy val configuration: Configuration = Configuration.default.withSnakeCaseMemberNames
@ConfiguredJsonCodec final case class ModelClass(someField1: String, someField2: Int, someField3: String)
我希望保持模型干净,而不添加外部框架的依赖项,因此它只包含特定于业务的案例类。
是否有可能避免添加注释@
例如,我们有一些case类 case class Foo(a: Int, b: List[String]) 我们希望反序列化json {"a": 1}中的Foo实例,用Nil替换缺少的b数组 我们可以为这样的行为创建自定义解码器 implicit val fooDecoder: Decoder[Foo] = (c: HCursor) =>
for {
a <- c.downField("a").as[Int]
b <- c.downField("b").as[Option[List[String]]
在使用slick中的circe获取json中的数据时,我可以获取实体中没有日期(Timestamp/DateTime)字段的数据。但是,当我在实体中使用Timestamp字段时,会引发错误:
[error] /var/www/html/scala-api/src/main/scala/oc/api/http/routes/TestApi.scala:40: could not find implicit value for parameter encoder: io.circe.Encoder[Seq[oc.api.models.UserEntity]]
[error]
假设我有多个ids类型,定义如下。
sealed trait Id {
val value: String
}
case class IdA(value: String) extends Id
case class IdB(value: String) extends Id
case class IdC(value: String) extends Id
这些类应该从JSON解码并编码到以下JSON。
{
"id: "some-id"
}
如何为id定义通用解码器/编码器,
case class A(id: IdA, name: String, coun
有没有可能用circe为MapString编写自定义解码器?我找到了这个,但它只是转换为Json: def mapToJson(map: Map[String, Any]): Json =
map.mapValues(anyToJson).asJson
def anyToJson(any: Any): Json = any match {
case n: Int => n.asJson
case n: Long => n.asJson
case n: Double => n.asJson
case s: String =>
我有这样一种情况,我必须有这个case class Config[F[_]](pattern: String, format:F[String]),因为有时格式应该存在,像Config[Id]一样使用它,有时不使用,并用Config[Option]制作它。问题是,这是如何应对Play或Spray的,以及序列化/反序列化这种结构的一些最佳实践是什么。我以前经常使用这个技巧,但从来没有强制序列化,直到我想知道读和写方法应该是什么样子。此外,如果有任何缺点或缺点,性能也是明智的。有什么想法吗?谢谢,各位!
我有我的circe解码器如下所示。我相信我的情绪解码器工作正确,所以不会包括在下面。
case class CryptoData(value: String, valueClassification: Sentiment)
implicit val decoder: Decoder[CryptoData] = Decoder.instance { json =>
for {
value <- json.downField("data").get[String]("value")
valu
我有一个JSON对象:
{"isCompany":false,"accommodations":[{"id":"00000000031000000067","isChecked":false,"name":"5 JULI 2017","addressLine1":"STRAAT 10 ","addressLine2":"1000 New York","nightsDeclared":0,"scho
如何为circe编写这样一个字符串编码器解码器?例如,我有
case class Something (s: String, foo: Foo, bar: Bar)
其中Bar是ADT的成员
trait Bar
case object A extends Bar
case object B extends Bar
在那里我想要破译我的东西
{
"s":"smstring",
"foo":{...somefoo...},
"bar":"aaa"//for Bar=A, or "bbb" for Bar