Oleg
Oleg

Reputation: 941

spray-json. How to get list of objects from json

I am trying to use akka-http-spray-json 10.0.9

My model:

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

I get json string jsonStr with list of persons and try to parse it:

implicit val personFormat: RootJsonFormat[Person] = jsonFormat3(Person)

val json = jsonStr.parseJson
val persons = json.convertTo[Seq[Person]]

Error:

Object expected in field 'id'


Probably i need to create implicit object extends RootJsonFormat[List[Person]] and override read and write methods.

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. Sorry for my english, it's not my native.

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} ]

Upvotes: 2

Views: 3783

Answers (1)

Michel Lemay
Michel Lemay

Reputation: 2094

I get perfectly expected results with:

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)

Upvotes: 2

Related Questions