Providing JsonFormat for a sequence of objects

I am trying to find help for applying JsonFormat extended for DefaultJsonProtocol to a class containing a sequence of objects.

So for classes:

class Person(val name: String, [......], val adresses: Seq[Adress])
class Adress(val streetname: String, val plz: BigDecimal, val city: String)

Now I would like to apply my JsonFormat:

object PersonJsonProtocol extends DefaultJsonProtocol {
  implicit object PersonJsonFormat extends RootJsonFormat[Person] {
    def write(pers: Person) = JsObject(
    "name" -> JsString(pers.name),
    [......],
    "adresses" -> JsArray(pers.adresses)
)
def read(value: JsValue) = {...}
}

But actually I'm not sure how to do this. I looked at the spray documentation and json, google, stackoverflow and Co. I am completely new to Scala / Spray and maybe I just don’t understand the point. So maybe someone here is so kind as to help me. Without an address sequence, I will work.

With JsArray, as shown in the example, I get a type mismatch. It scans the list [JsValue], but also converts it to a list of inconsistencies.

AdressJsonProtocol : "" → AdressJsonFormat.write(pers.adresses), ...

+4
2

spray.json.CollectionFormats.

:

import spray.json._

class Adress(val streetname: String, val plz: BigDecimal, val city: String)

class Person(val name: String, val adresses: Seq[Adress])

object PersonJsonProtocol extends DefaultJsonProtocol {
  implicit object AdressJsonFormat extends RootJsonFormat[Adress] {
    def write(addr: Adress) = JsObject(Map(
      "streetname" -> JsString(addr.streetname),
      "plz" -> JsNumber(addr.plz),
      "city" -> JsString(addr.city)
    ))
    def read(value: JsValue): Adress = ???
  }
  implicit object PersonJsonFormat extends RootJsonFormat[Person] {
    def write(pers: Person) = JsObject(Map(
      "name" -> JsString(pers.name),
      "adresses" -> JsArray(pers.adresses.map(_.toJson).toList)
    ))
    def read(value: JsValue): Person = ???
  }
}

object Main extends App {
  import PersonJsonProtocol._
  val person = new Person("joe", Seq(new Adress("street", 123, "city")))
  println("poso default toString: %s".format(person))
  val personJVal = person.toJson
  println("JValue toString: %s".format(personJVal))
  val personJson = personJVal.prettyPrint
  println("pretty-printing: %s".format(personJson))
}

:

poso default toString: Person@680ccad
JValue toString: {"name":"joe","adresses":[{"streetname":"street","plz":123,"city":"city"}]}
pretty-printing: {
  "name": "joe",
  "adresses": [{
    "streetname": "street",
    "plz": 123,
    "city": "city"
  }]
}
+2

DefaultJsonProtocol case, , (, ...)

case ?

implicit val formatPerson = jsonFormat6(Adress)
implicit val formatAddress = jsonFormat3(Adress)

jsonFormat'number ' case.

- Person.

+9

Source: https://habr.com/ru/post/1526750/


All Articles