喷-json。如何从 json 获取对象列表
spray-json. How to get list of objects from 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]]
错误:
Object expected in field 'id'
可能我需要创建 implicit object extends RootJsonFormat[List[Person]]
并覆盖 read
和 write
方法。
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 :(
}
}
P.S.对不起我的英语,不是我的母语。
UPD
json链:
[ {"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)
我正在尝试使用 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]]
错误:
Object expected in field 'id'
可能我需要创建 implicit object extends RootJsonFormat[List[Person]]
并覆盖 read
和 write
方法。
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 :(
}
}
P.S.对不起我的英语,不是我的母语。
UPD
json链:
[ {"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)