Scala Circe与泛型 [英] Scala Circe with generics

查看:170
本文介绍了Scala Circe与泛型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用scala json库Circe,将其包装为简单特征以提供往返于json的转换,

I am trying to use the scala json library Circe, wrapping it in a simple trait to provide conversion to/from json for which I have the following:

import io.circe.generic.auto._
import io.circe.parser._
import io.circe.syntax._

trait JsonConverter {
  def toJson[T](t : T) : String
  def fromJson[T](s: String) : T
}

case class CirceJsonConverter() extends JsonConverter{
  override def toJson[T](t: T): String = t.asJson.noSpaces
  override def fromJson[T](s: String): T = decode[T](s).getOrElse(null).asInstanceOf[T]
}

这样做的目的是简单地能够使用任何对象调用JsonConverter并将其像jsonConverter.toJson(0) must equalTo("0")一样将其转换为json或从json转换,但是当我尝试对其进行编译时,我得到以下信息:

The aim of this is to simply be able to call JsonConverter with any object and have it convert it to/from json as such jsonConverter.toJson(0) must equalTo("0") , however when I try to compile it I get the following:

[error] could not find implicit value for parameter encoder: io.circe.Encoder[T]
[error]   override def toJson[T](t: T): String = t.asJson.noSpaces
[error]                                            ^
[error] could not find implicit value for parameter decoder: io.circe.Decoder[T]
[error]   override def fromJson[T](s: String): T = decode[T](s).getOrElse(null).asInstanceOf[T]
[error]                                                     ^
[error] two errors found

我当然可以拥有一个类,我打算通过转换器放入的所有内容都可以继承,但是我有一个印象,circe可以自动生成编码器/解码器?

I can of course have a class that everything I intend to put through the converter inherit from, but I had the impression that circe could auto generate the encoders/decoders?

推荐答案

除非您可以实施将任何对象转换为Json的策略,否则所需的内容将无法正常工作.相反,Circe(以及许多其他库)选择使用一种称为类型类"的通用模式,以便于定义特定类型的 /Decoder时要方便地定义自己想做的事情.

What you want is not going to work unless you can implement a strategy for turning any object into Json... which seems unlikely. Circe (and many other libs) instead choose to use a common pattern called Type Classes to make it convenient to define how you want to do something, in this case Encoder/Decoder, for a specific type.

如果您不熟悉类型类,我建议您对其进行研究.然后查看Circe文档,了解如何专门实现编码器/解码器.

I recommend researching Type Classes if you are unfamiliar with them. And then take a look at the Circe docs to see how you can implement Encoders/Decoders specifically.

这篇关于Scala Circe与泛型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆