Scala 编译错误:"No implicit view available"和"diverging implicit expansion"


 def MyFun(result: ListBuffer[(String, DateTime, List[(String, Int)])]):
 String = {
 val json =
  (result.map {
    item => (
      ("subject" -> item._1) ~
        ("time" -> item._2) ~
        ("student" -> item._3.map {
          student_description=> (
            ("name" -> lb_result._1) ~
              ("age" -> lb_result._2) 
            )
        })
      )
    }
    )
    val resultFormat = compact(render(json))
    resultFormat  
}

错误1:没有从org.joda.time.DateTime => org.json4s.JsonAST.JValue中获得隐式视图。("subject" -> item._1) ~

错误2:none类型的发散式隐式展开=> org.json4s.JsonAST。从trait JsonDSL中的seq2jvalue方法开始val resultFormat = compact(render(json))

我暗示了json4s-ext对于joda-time的支持,但是仅仅导入这个子模块并不能解决您的问题。

JsonDSL用于创建JValues,而序列化器仅用于将JValues转换为JSON,反之亦然(序列化和反序列化)。

如果我们尝试用DateTime创建一个更简单的json对象:

val jvalue = ("subj" -> "foo") ~ ("time" -> DateTime.now)

得到相同的错误:

error: No implicit view available from org.joda.time.DateTime => org.json4s.JsonAST.JValue.

就像我说的,当我们使用JsonDSL创建JValues时,不使用来自json4s-extDateTime序列化器。

你可以创建一个隐式函数DateTime => JValueDateTime.now.getMillisDateTime.now.toString来分别创建一个JIntJString,但是如果joda时间序列化器已经存在,我们为什么要重新发明轮子呢?

我们可以引入一些case类来保存result中的数据,然后json4s可以为我们序列化它们:

import scala.collection.mutable.ListBuffer
import com.github.nscala_time.time.Imports._
import org.json4s._
import org.json4s.JsonDSL._
import org.json4s.native.JsonMethods._
import org.json4s.native.Serialization
import org.json4s.native.Serialization.{read, write}
implicit val formats = 
  Serialization.formats(NoTypeHints) ++ org.json4s.ext.JodaTimeSerializers.all
case class Lesson(subject: String, time: org.joda.time.DateTime, students: List[Student])
case class Student(name: String, age: Int)
val result = ListBuffer(("subj", DateTime.now, ("Alice", 20) :: Nil))
val lessons =  result.map { case (subj, time, students) => 
  Lesson(subj, time, students.map(Student.tupled))
}
write(lessons)
// String = [{"subject":"subj","time":"2015-09-09T11:22:59.762Z","students":[{"name":"Alice","age":20}]}]

请注意,您仍然需要像Andreas Neumann解释的那样添加json4s-ext

Peter Neyens已经说过,要序列化org.joda.time.DateTime,您需要ext包

https://github.com/json4s/json4s临时演员

将此依赖项添加到您的build.sbt

libraryDependencies += "org.json4s" %% "json4s-ext" % "3.2.11"

相关内容

最新更新