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
}
错误一: org.joda.time.DateTime => org.json4s.JsonAST.JValue.("subject"-> item._1) 没有可用的隐式 View ~
错误 2:类型 Nothing => org.json4s.JsonAST.JValue 的发散隐式扩展以特征 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-ext 的 DateTime
的序列化程序。
您可以创建隐式函数 DateTime => JValue
或执行类似 DateTime.now.getMillis
或 DateTime.now.toString
的操作以分别创建一个 JInt
或一个 JString
,但如果 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。
关于Scala 编译错误 : "No implicit view available" and "diverging implicit expansion",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32476490/