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
}
Run Code Online (Sandbox Code Playgroud)
错误1:org.joda.time.DateTime => org.json4s.JsonAST.JValue没有隐式视图.("subject" - > item._1)〜
错误2:类型Nothing => org.json4s.JsonAST.JValue的分散隐式扩展从特征中的方法seq2jvalue开始JSONDSL val resultFormat = compact(render(json))
我暗示了json4s-ext的joda-time支持,但只导入这个子模块不能解决你的问题.
JsonDSL用于创建JValues,序列化器仅用于转换JValues为JSON,反之亦然(序列化和反序列化).
如果我们尝试用以下代码创建一个更简单的json对象DateTime:
val jvalue = ("subj" -> "foo") ~ ("time" -> DateTime.now)
Run Code Online (Sandbox Code Playgroud)
我们得到了同样的错误:
error: No implicit view available from org.joda.time.DateTime => org.json4s.JsonAST.JValue.
Run Code Online (Sandbox Code Playgroud)
就像我说的,当我们使用JsonDSL创建时,不使用DateTime来自json4s-ext的序列化器JValues.
您可以创建隐式函数DateTime => JValue或执行类似DateTime.now.getMillis或DateTime.now.toString分别创建a JInt或a的操作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}]}]
Run Code Online (Sandbox Code Playgroud)
请注意,你仍然需要像Andreas Neumann解释的那样添加json4s-ext.