i`m trying here to find some help to apply an JsonFormat extended of the DefaultJsonProtocol to an class containing a Sequence of Objects.
So for the 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 am not sure how to do it. I searched through the spray-json documentation and throug google, stackoverflow & Co. I am totally new to Scala/Spray and perhaps i am just missing the point. So perhaps somebody here is so kind to help me. Without the Adress sequence i will work.
With the JsArray as provided in the example i get an type mismatch. It is exspecting an List[JsValue] but also with converting to list the mismatch still stands.
I also tried to inserts an seperate AdressJsonProtocol and include it via: "addresses" -> AdressJsonFormat.write(pers.adresses) but yet again it is an Sequence...
Look at the source of
spray.json.CollectionFormats
.Here is a runnable implementation:
which yields:
You don't need to write a DefaultJsonProtocol for each case class, except if you want some special logic (formatting, filtering ...)
Have you tried to simply use the default case class serialization?
The number in jsonFormat'number' stands for the number of members in your case class.
Then spray-json will take care of your nested Address collection when serializing a Person.