json - 特征类型参数的隐式编码器

标签 json scala traits argonaut

我想使用 argonaut lib 将 List[E] 类型的字段编码为 json。

sealed trait Msg[E] {
  val contents: List[E]    

  def send(): Unit = {
    val json = contents.asJson
    println("Sending json: " + json.toString())
  }
}

然后我有一个 StringMsg 案例类:

case class StringMsg(contents: List[String]) extends Msg[String]

argonaut 库定义了 JsonIdentity[J] 特征:

trait JsonIdentity[J] {
  val j: J

  /**
   * Encode to a JSON value using the given implicit encoder.
   */
  def jencode(implicit e: EncodeJson[J]): Json =
    e(j)
}

当我创建 StringMsg 的新实例并调用 send() 方法时,出现以下错误:

StringMsg(List("a","b")).send()

could not find implicit value for parameter e: argonaut.EncodeJson[List[E]]

最佳答案

您的 API 应要求客户端代码中隐式 argonaut.EncodeJson[List[E]]:

sealed trait Msg[E] {
  val contents: List[E]
  implicit def encodeJson: argonaut.EncodeJson[List[E]] //to be implemented in subclass   

  def send(): Unit = {
    val json = contents.asJson
    println("Sending json: " + json.toString())
  }
}

//or

abstract class Msg[E](implicit encodeJson: argonaut.EncodeJson[List[E]]) {
  val contents: List[E]

  def send(): Unit = {
    val json = contents.asJson
    println("Sending json: " + json.toString())
  }
}

//or

sealed trait class Msg[E] {
  val contents: List[E]

  def send()(implicit encodeJson: argonaut.EncodeJson[List[E]]): Unit = {
    val json = contents.asJson
    println("Sending json: " + json.toString())
  }
}

客户端代码中的某处:

case class StringMsg(contents: List[String]) extends Msg[String] { 
   implicit val encodeJson = argonaut.StringEncodeJson 
}

//or

import argonaut.StringEncodeJson //or even import argonaut._
case class StringMsg(contents: List[String]) extends Msg[String]() //implicit will be passed here

//or

import argonaut.StringEncodeJson //or even import argonaut._
case class StringMsg(contents: List[String]) extends Msg[String]
val a = StringMsg(Nil)
a.send() //implicit will be passed here

关于json - 特征类型参数的隐式编码器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29493148/

相关文章:

javascript - Ruby on Rails,json 与 js ajax 响应

scala - 做 sbt ! : output to file

Scala REPL 在 Ubuntu 上不起作用

rust - 为什么不能将 Box<dyn Trait> 传递给以 &mut Trait 作为参数的函数

swing - 如何使用 SuperMixin 创建 Scala swing 包装类?

javascript - 使用维基百科的 opensearch api 时,主题标签符号不会填充数据列表。为什么?

javascript - 将键、值 JSON 数组转换为表格 JSON 格式

javascript - Highchart - 将更多系列添加到多个同步的 Highstock 图表之一

scala - 尝试从 Scala 中的其他类型生成类型

具有由实现定义的常量字段的 Rust 特征