喷-json.如何从 json 获取对象列表



我正在尝试使用akka-http-spray-json 10.0.9

我的模型:

case class Person(id: Long, name: String, age: Int)

我得到带有人员列表的 json 字符串jsonStr并尝试解析它:

implicit val personFormat: RootJsonFormat[Person] = jsonFormat3(Person)
val json = jsonStr.parseJson
val persons = json.convertTo[Seq[Person]]

错误:

字段"id"中应包含的对象


可能我需要创建implicit object extends RootJsonFormat[List[Person]]并覆盖readwrite方法。

implicit object personsListFormat extends RootJsonFormat[List[Person]] {
override def write(persons: List[Person]) = ???
override def read(json: JsValue) = {
// Maybe something like
// json.map(_.convertTo[Person])
// But there is no map or similar method :(
}
}

附言对不起我的英语,这不是我的母语。

UPD
jsonStr:

[ {"id":6,"name":"Martin Ordersky","age":50}, {"id":8,"name":"Linus Torwalds","age":43}, {"id":9,"name":"James Gosling","age":45}, {"id":10,"name":"Bjarne Stroustrup","age":59} ]

我得到了完美的预期结果:

import spray.json._
object MyJsonProtocol extends DefaultJsonProtocol {
implicit val personFormat: JsonFormat[Person] = jsonFormat3(Person)
}
import MyJsonProtocol._
val jsonStr = """[{"id":1,"name":"john","age":40}]"""
val json = jsonStr.parseJson
val persons = json.convertTo[List[Person]]
persons.foreach(println)

最新更新